package com.ssy.lingxi.transaction.serviceimpl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.StrUtil;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.ssy.lingxi.common.constant.CommonConstant;
import com.ssy.lingxi.common.constant.Constants;
import com.ssy.lingxi.common.exception.BusinessException;
import com.ssy.lingxi.common.model.dto.UserLoginCacheDTO;
import com.ssy.lingxi.common.model.vo.PageVO;
import com.ssy.lingxi.common.response.PageData;
import com.ssy.lingxi.common.response.ResponseCode;
import com.ssy.lingxi.common.response.Wrapper;
import com.ssy.lingxi.component.redis.service.IRedisStringUtils;
import com.ssy.lingxi.member.merchant.api.feign.inner.MemberInnerControllerFeign;
import com.ssy.lingxi.member.merchant.api.model.vo.inner.request.MemberFeignRelationVO;
import com.ssy.lingxi.member.merchant.api.model.vo.inner.response.MemberFeignLogoVO;
import com.ssy.lingxi.member.merchant.api.model.vo.inner.response.MemberSalesFeignVO;
import com.ssy.lingxi.member.merchant.api.feign.inner.MemberAbilitySalesFeign;
import com.ssy.lingxi.member.merchant.api.model.vo.inner.request.MemberSalesFindMemberVO;
import com.ssy.lingxi.member.merchant.api.model.vo.inner.response.MemberSalesFindMemberQueryVO;
import com.ssy.lingxi.message.api.constant.MessageTemplateCode;
import com.ssy.lingxi.message.api.feign.SystemMessageControllerFeign;
import com.ssy.lingxi.message.api.vo.request.SystemMessageRequest;
import com.ssy.lingxi.product.api.feign.ICommodityFeign;
import com.ssy.lingxi.product.api.model.response.commodity.CommodityGoodsResponse;
import com.ssy.lingxi.report.api.enums.CommodityInquiryOperateTypeEnum;
import com.ssy.lingxi.report.api.enums.OperateDataSourceEnum;
import com.ssy.lingxi.report.api.feign.ReportControllerFeign;
import com.ssy.lingxi.report.api.vo.request.OperateNoticeVO;
import com.ssy.lingxi.transaction.api.common.OrderConstant;
import com.ssy.lingxi.transaction.api.dto.request.*;
import com.ssy.lingxi.transaction.api.dto.response.*;
import com.ssy.lingxi.transaction.api.enums.InquiryExternalStatusEnum;
import com.ssy.lingxi.transaction.api.enums.InquiryInteriorStatusEnum;
import com.ssy.lingxi.transaction.api.enums.InquiryOperationEnum;
import com.ssy.lingxi.transaction.api.enums.QuoteInteriorStatusEnum;
import com.ssy.lingxi.transaction.entity.CommodityArea;
import com.ssy.lingxi.transaction.api.common.InquirySortTypeConstants;
import com.ssy.lingxi.transaction.entity.Inquiry;
import com.ssy.lingxi.transaction.entity.InquiryProduct;
import com.ssy.lingxi.transaction.entity.record.InquiryExternalRecord;
import com.ssy.lingxi.transaction.entity.record.InquiryInteriorRecord;
import com.ssy.lingxi.transaction.repository.InquiryExternalRecordRepository;
import com.ssy.lingxi.transaction.repository.InquiryInteriorRecordRepository;
import com.ssy.lingxi.transaction.repository.InquiryProductRepository;
import com.ssy.lingxi.transaction.repository.InquiryRepository;
import com.ssy.lingxi.transaction.service.IInquiryService;
import com.ssy.lingxi.transaction.utils.TradeUtils;
import com.ssy.lingxi.workflow.api.feign.ProcessFeign;
import com.ssy.lingxi.workflow.api.model.contant.ProcessEnum;
import com.ssy.lingxi.workflow.api.model.vo.request.ExternalProcessQueryVO;
import com.ssy.lingxi.workflow.api.model.vo.request.InternalProcessQueryVO;
import com.ssy.lingxi.workflow.api.model.vo.request.TaskExecuteVO;
import com.ssy.lingxi.workflow.api.model.vo.request.TaskStartVO;
import com.ssy.lingxi.workflow.api.model.vo.response.SimpleProcessDefVO;
import com.ssy.lingxi.workflow.api.model.vo.response.SimpleTaskCompleteVO;
import com.ssy.lingxi.workflow.api.model.vo.response.SimpleTaskVO;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ObjectUtils;

import javax.annotation.Resource;
import javax.persistence.criteria.Order;
import javax.persistence.criteria.Predicate;
import java.util.*;
import java.util.concurrent.CompletableFuture;
import java.util.stream.Collectors;

/**
 * 商品询价单管理
 *
 * @author wrc
 * @date 2020/8/10
 */

@Slf4j
@Service
public class InquiryServiceImpl implements IInquiryService {

    @Resource
    InquiryRepository inquiryRepository;

    @Resource
    InquiryProductRepository inquiryProductRepository;

    @Resource
    InquiryInteriorRecordRepository inquiryInteriorRecordRepository;

    @Resource
    InquiryExternalRecordRepository inquiryExternalRecordRepository;

    @Resource
    SystemMessageControllerFeign systemMessageControllerFeign;
    
    @Resource
    ProcessFeign processFeign;

    @Resource
    ReportControllerFeign reportControllerFeign;

    @Resource
    MemberInnerControllerFeign memberInnerControllerFeign;

    @Resource
    ICommodityFeign commodityFeign;

    @Resource
    private IRedisStringUtils redisStringUtils;

    @Resource
    private MemberAbilitySalesFeign memberAbilitySalesFeign;

    /**
     * 询价报价-待分配询价单查询
     */
    @Override
    public Wrapper<PageData<NotAssignedInquiryResponse>> notAssignedInquiryList(NotAssignedInquiryRequest request, UserLoginCacheDTO sysUser) {
        Pageable page = PageRequest.of(request.getCurrent(), request.getPageSize());
        Page<Inquiry> result = inquiryRepository.findAll(getNotAssignedInquirySpecification(request, sysUser.getMemberId(), sysUser.getMemberRoleId()), page);
        List<NotAssignedInquiryResponse> inquiryListResponseList = result.getContent().stream().map(inquiry -> {
            NotAssignedInquiryResponse quoteListResponse = BeanUtil.copyProperties(inquiry, NotAssignedInquiryResponse.class);
            quoteListResponse.setExternalStateName(InquiryExternalStatusEnum.getName(quoteListResponse.getExternalState()));
            quoteListResponse.setInteriorStateName(QuoteInteriorStatusEnum.getName(quoteListResponse.getInteriorState()));
            quoteListResponse.setInquiryListMemberName(inquiry.getCreateMemberName());
            quoteListResponse.setInquiryListMemberId(inquiry.getCreateMemberId());
            return quoteListResponse;
        }).collect(Collectors.toList());
        return Wrapper.success(new PageData<>(result.getTotalElements(), inquiryListResponseList));
    }

    /**
     * 商品询价-询价单列表
     */
    @Override
    public Wrapper<PageData<InquiryListResponse>> inquiryAddList(InquiryListRequest request, UserLoginCacheDTO sysUser) {
        Pageable page = PageRequest.of(request.getCurrent(), request.getPageSize());
        Page<Inquiry> result = inquiryRepository.findAll(getSpecification(request, sysUser.getMemberId(), sysUser.getMemberRoleId(), null, null, OrderConstant.InquiryQueryType.INQUIRY_ALL), page);
        List<InquiryListResponse> inquiryListResponseList = result.getContent().stream().map(inquiry -> {
            InquiryListResponse inquiryListResponse = BeanUtil.copyProperties(inquiry, InquiryListResponse.class);
            inquiryListResponse.setExternalStateName(InquiryExternalStatusEnum.getName(inquiryListResponse.getExternalState()));
            inquiryListResponse.setInteriorStateName(InquiryInteriorStatusEnum.getName(inquiryListResponse.getInteriorState()));
            inquiryListResponse.setInquiryListMemberName(inquiry.getCreateMemberName());
            inquiryListResponse.setInquiryListMemberId(inquiry.getCreateMemberId());
            List<InquiryProduct> inquiryProductList = inquiry.getInquiryProductList();
            if(!CollectionUtils.isEmpty(inquiryProductList)){
                inquiryListResponse.setImgUrl(inquiryProductList.get(0).getImgUrl());
            }
            if(InquiryInteriorStatusEnum.TO_BE_SUBMITTED_FOR_REVIEW.getState().equals(inquiryListResponse.getInteriorState())){
                inquiryListResponse.setIsSubmit(true);
                inquiryListResponse.setIsUpdate(true);
                inquiryListResponse.setIsDelete(true);
            }else{
                inquiryListResponse.setIsUpdate(true);
            }
            return inquiryListResponse;
        }).collect(Collectors.toList());
        return Wrapper.success(new PageData<>(result.getTotalElements(), inquiryListResponseList));
    }

    /**
     * 交易中心-商品询价-待新增询价单列表查询
     */
    @Override
    public Wrapper<PageData<InquiryListResponse>> inquiryList(InquiryListRequest request, UserLoginCacheDTO sysUser) {
        Pageable page = PageRequest.of(request.getCurrent(), request.getPageSize());
        Page<Inquiry> result = inquiryRepository.findAll(getSpecification(request, sysUser.getMemberId(), sysUser.getMemberRoleId(), null, null, OrderConstant.InquiryQueryType.INQUIRY_NOT_SUBMIT), page);
        List<InquiryListResponse> inquiryListResponseList = result.getContent().stream().map(inquiry -> {
            InquiryListResponse inquiryListResponse = BeanUtil.copyProperties(inquiry, InquiryListResponse.class);
            inquiryListResponse.setExternalStateName(InquiryExternalStatusEnum.getName(inquiryListResponse.getExternalState()));
            inquiryListResponse.setInteriorStateName(InquiryInteriorStatusEnum.getName(inquiryListResponse.getInteriorState()));
            inquiryListResponse.setInquiryListMemberName(inquiry.getCreateMemberName());
            inquiryListResponse.setInquiryListMemberId(inquiry.getCreateMemberId());
            List<InquiryProduct> inquiryProductList = inquiry.getInquiryProductList();
            if(!CollectionUtils.isEmpty(inquiryProductList)){
                inquiryListResponse.setImgUrl(inquiryProductList.get(0).getImgUrl());
            }
            if(InquiryInteriorStatusEnum.TO_BE_SUBMITTED_FOR_REVIEW.getState().equals(inquiryListResponse.getInteriorState())){
                inquiryListResponse.setIsSubmit(true);
                inquiryListResponse.setIsUpdate(true);
                inquiryListResponse.setIsDelete(true);
            }else{
                inquiryListResponse.setIsUpdate(true);
            }
            return inquiryListResponse;
        }).collect(Collectors.toList());
        return Wrapper.success(new PageData<>(result.getTotalElements(), inquiryListResponseList));
    }


    /**
     * 交易能力 询价报价 询价单查询
     * @author wrc
     * @date 2020/8/12
     */
    @Override
    public Wrapper<PageData<QuoteListResponse>> productInquiryList(InquiryListRequest request, UserLoginCacheDTO sysUser) {
        Pageable page = PageRequest.of(request.getCurrent(), request.getPageSize());
        Page<Inquiry> result = inquiryRepository.findAll(getSpecification(request, null, null, sysUser.getMemberId(), sysUser.getMemberRoleId(), OrderConstant.InquiryQueryType.PRODUCT_QUOTATION_TO_BE_SUBMITTED), page);
        List<QuoteListResponse> inquiryListResponseList = result.getContent().stream().map(inquiry -> {
            QuoteListResponse quoteListResponse = BeanUtil.copyProperties(inquiry, QuoteListResponse.class);
            quoteListResponse.setExternalStateName(InquiryExternalStatusEnum.getName(quoteListResponse.getExternalState()));
            quoteListResponse.setInteriorStateName(QuoteInteriorStatusEnum.getName(quoteListResponse.getInteriorState()));
            quoteListResponse.setInquiryListMemberName(inquiry.getCreateMemberName());
            quoteListResponse.setInquiryListMemberId(inquiry.getCreateMemberId());
            quoteListResponse.setIsShowQuote(InquiryExternalStatusEnum.QUOTATION_TO_BE_SUBMITTED.getState().equals(quoteListResponse.getExternalState()));
            return quoteListResponse;
        }).collect(Collectors.toList());
        return Wrapper.success(new PageData<>(result.getTotalElements(), inquiryListResponseList));
    }

    /**
     * 交易中心-商品询价-待新增询价单添加
     * @author wrc
     * @date 2020/8/10
     */
    @Transactional
    @Override
    public Wrapper<Long> inquiryListAdd(InquiryListAddRequest request, UserLoginCacheDTO sysUser) {
        //判断商品是否有库存
        List<InquiryListProductRequest> inquiryProductRequests = request.getInquiryListProductRequests();

        //询价单
        Inquiry inquiry = new Inquiry();
        inquiry.setShopId(request.getShopId());
        inquiry.setContactId(request.getContactId());
        inquiry.setContactName(request.getContactName());
        inquiry.setPhoneCode(request.getPhoneCode());
        inquiry.setContactPhone(request.getContactPhone());
        inquiry.setCreateMemberId(sysUser.getMemberId());
        inquiry.setCreateMemberName(sysUser.getCompany());
        inquiry.setCreateRoleId(sysUser.getMemberRoleId());
        inquiry.setCreateRoleName(sysUser.getMemberRoleName());
        inquiry.setUserId(sysUser.getUserId());
        inquiry.setUserName(sysUser.getUserName());
        inquiry.setVoucherTime(System.currentTimeMillis());
        inquiry.setIsQuoted(OrderConstant.State.STOP);
        inquiry.setUpdateTime(System.currentTimeMillis());
        inquiry.setTaxes(request.getTaxes());
        inquiry.setCreateMemberName(sysUser.getCompany());
        inquiry.setQuotationAsTime(request.getQuotationAsTime());
        inquiry.setPaymentType(request.getPaymentType());
        inquiry.setPackRequire(request.getPackRequire());
        inquiry.setOtherRequire(request.getOtherRequire());
        inquiry.setOffer(request.getOffer());
        inquiry.setMemberName(request.getMemberName());
        inquiry.setMemberRoleId(request.getMemberRoleId());
        inquiry.setMemberRoleName(request.getMemberRoleName());
        inquiry.setMemberId(request.getMemberId());
        inquiry.setLogistics(request.getLogistics());
        inquiry.setInquiryListNo(TradeUtils.randomUniqueNumber(TradeUtils.INQUIRY_LIST_NO));
        inquiry.setFullAddress(request.getFullAddress());
        inquiry.setFullAddressId(request.getFullAddressId());
        inquiry.setEnclosureUrls(request.getEnclosureUrls());
        inquiry.setDeliveryTime(request.getDeliveryTime());
        inquiry.setDetails(request.getDetails());
        inquiry.setCreateTime(System.currentTimeMillis());

        //查询当前登录用户是否有业务员
        List<MemberFeignRelationVO> memberFeignRelationVOList = new ArrayList<>();
        MemberFeignRelationVO memberFeignRelationVO = new MemberFeignRelationVO();
        memberFeignRelationVO.setUpperMemberId(request.getMemberId());
        memberFeignRelationVO.setUpperRoleId(request.getMemberRoleId());
        memberFeignRelationVO.setSubMemberId(sysUser.getMemberId());
        memberFeignRelationVO.setSubRoleId(sysUser.getMemberRoleId());
        memberFeignRelationVOList.add(memberFeignRelationVO);
        Wrapper<List<MemberSalesFeignVO>> memberSales = memberInnerControllerFeign.findMemberSales(memberFeignRelationVOList);
        if(ResponseCode.SUCCESS.getCode() == memberSales.getCode()){
            List<MemberSalesFeignVO> data = memberSales.getData();
            if(!CollectionUtils.isEmpty(data)){
                MemberSalesFeignVO memberSalesFeignVO = data.get(0);
                if(memberSalesFeignVO != null){
                    Long userId = memberSalesFeignVO.getUserId();
                    if(userId != null && userId > 0){
                        inquiry.setQuoteUserId(userId);
                    }
                }
            }

        }

        //询价商品
        HashMap<Long, CommodityGoodsResponse> commodityMap = new HashMap<>();
        List<Long> commoditySkuIdList = inquiryProductRequests.stream().map(InquiryListProductRequest::getProductId).collect(Collectors.toList());
        Wrapper<List<CommodityGoodsResponse>> result = commodityFeign.getCommodityByCommoditySkuIdList(commoditySkuIdList);
        if(ResponseCode.SUCCESS.getCode() == result.getCode()){
            List<CommodityGoodsResponse> commodityGoodsResponseList = result.getData();
            commodityGoodsResponseList.forEach(commodityGoodsResponse -> commodityMap.put(commodityGoodsResponse.getId(), commodityGoodsResponse));

            List<String> memberList = new ArrayList<>();
            List<InquiryProduct> inquiryProductList = inquiryProductRequests.stream().map(inquiryProductRequest -> {
                CommodityGoodsResponse commodityGoodsResponse = commodityMap.get(inquiryProductRequest.getProductId());
                if(commodityGoodsResponse != null){
                    Long upperCommoditySkuId = commodityGoodsResponse.getCommodityUnitPriceAndPicId();
                    Long upperMemberId = commodityGoodsResponse.getUpperMemberId();
                    String upperMemberName = commodityGoodsResponse.getUpperMemberName();
                    Long upperMemberRoleId = commodityGoodsResponse.getUpperMemberRoleId();
                    String upperMemberRoleName = commodityGoodsResponse.getUpperMemberRoleName();

                    //用来判断询价商品是否是同一个会员
                    if(upperCommoditySkuId != null && upperCommoditySkuId > 0){
                        String member = upperMemberId + "_" + upperMemberRoleId;
                        String upperMember = inquiry.getMemberId() + "_" + inquiry.getMemberRoleId();
                        if(!memberList.contains(member) && !upperMember.equals(member)){
                            memberList.add(member);
                        }
                    }
                    //税率
                    Double taxRate = commodityGoodsResponse.getTaxRate();

                    InquiryProduct inquiryProduct = new InquiryProduct();
                    inquiryProduct.setBrand(inquiryProductRequest.getBrand());
                    inquiryProduct.setPurchaseCount(inquiryProductRequest.getPurchaseCount());
                    inquiryProduct.setProductName(inquiryProductRequest.getProductName());
                    inquiryProduct.setProductId(inquiryProductRequest.getProductId());
                    inquiryProduct.setUnit(inquiryProductRequest.getUnit());
                    inquiryProduct.setCategory(inquiryProductRequest.getCategory());
                    inquiryProduct.setLogistics(inquiryProductRequest.getLogistics());
                    inquiryProduct.setCommodityId(inquiryProductRequest.getCommodityId());
                    inquiryProduct.setMemberRoleId(request.getMemberRoleId());
                    inquiryProduct.setMemberId(request.getMemberId());
                    inquiryProduct.setInquiry(inquiry);
                    inquiryProduct.setImgUrl(commodityGoodsResponse.getMainPic());
                    inquiryProduct.setTaxRate(taxRate);
                    inquiryProduct.setUpperCommoditySkuId(upperCommoditySkuId);
                    inquiryProduct.setUpperMemberId(upperMemberId);
                    inquiryProduct.setUpperMemberRoleId(upperMemberRoleId);
                    inquiryProduct.setUpperMemberName(upperMemberName);
                    inquiryProduct.setUpperMemberRoleName(upperMemberRoleName);
                    //商品销售区域
                    inquiryProduct.setIsAllArea(commodityGoodsResponse.getIsAllArea());
                    List<com.ssy.lingxi.product.api.model.response.commodity.CommodityAreaResponse> commodityAreaResponseList = commodityGoodsResponse.getCommodityAreaList();
                    if(!CollectionUtils.isEmpty(commodityAreaResponseList)){
                        List<CommodityArea> commodityAreaList = commodityAreaResponseList.stream().map(commodityAreaResponse -> {
                            CommodityArea commodityArea = BeanUtil.copyProperties(commodityAreaResponse, CommodityArea.class);
                            commodityArea.setInquiryProduct(inquiryProduct);
                            return commodityArea;
                        }).collect(Collectors.toList());
                        inquiryProduct.setCommodityAreaList(commodityAreaList);
                    }
                    return inquiryProduct;
                }else{
                    throw new BusinessException(ResponseCode.PRODUCT_COMMODITY_NOT_EXIST);
                }
            }).collect(Collectors.toList());
            inquiry.setInquiryProductList(inquiryProductList);
            inquiryRepository.saveAndFlush(inquiry);

            //根据被询价商品所属会员来判断是否可以进行二次询价
            int memberSize = memberList.size();
            if(memberSize > 0){
                inquiry.setIsSecondInquiry(memberSize == 1);
            }

            //启动流程
            TaskStartVO processStartVO = new TaskStartVO();
            processStartVO.setDataId(inquiry.getId());
            processStartVO.setRoleId(sysUser.getMemberRoleId());
            processStartVO.setMemberId(sysUser.getMemberId());
            processStartVO.setProcessKey(ProcessEnum.TRADE_INQUIRY_INNER.getProcessKey());
            Wrapper<SimpleTaskCompleteVO> taskResultVOWrapper = processFeign.startSimpleProcess(processStartVO);
            if (ResponseCode.SUCCESS.getCode() != taskResultVOWrapper.getCode()) {
                return Wrapper.fail(taskResultVOWrapper.getCode(), taskResultVOWrapper.getMessage());
            }
            TaskStartVO processStartVOExternal = new TaskStartVO();
            processStartVOExternal.setDataId(inquiry.getId());
            processStartVOExternal.setRoleId(sysUser.getMemberRoleId());
            processStartVOExternal.setMemberId(sysUser.getMemberId());
            processStartVOExternal.setProcessKey(ProcessEnum.TRADE_INQUIRY_EXTERNAL.getProcessKey());
            Wrapper<SimpleTaskCompleteVO> taskResultVOWrapperExternal = processFeign.startSimpleProcess(processStartVOExternal);
            if (ResponseCode.SUCCESS.getCode() != taskResultVOWrapperExternal.getCode()) {
                return Wrapper.fail(taskResultVOWrapperExternal.getCode(), taskResultVOWrapperExternal.getMessage());
            }
            inquiry.setExternalTaskId(taskResultVOWrapperExternal.getData().getTaskId());
            inquiry.setExternalState(taskResultVOWrapperExternal.getData().getStatus());
            inquiry.setInteriorTaskId(taskResultVOWrapper.getData().getTaskId());
            inquiry.setInteriorState(taskResultVOWrapper.getData().getStatus());

            inquiryRepository.saveAndFlush(inquiry);

            //记录日志
            InquiryInteriorRecord interiorInquiryListLog = new InquiryInteriorRecord();
            interiorInquiryListLog.setCreateRoleId(sysUser.getMemberRoleId());
            interiorInquiryListLog.setUpdateTime(System.currentTimeMillis());
            interiorInquiryListLog.setState(taskResultVOWrapper.getData().getStatus());
            interiorInquiryListLog.setRoleName(sysUser.getUserName());
            interiorInquiryListLog.setRoleId(sysUser.getMemberRoleId());
            interiorInquiryListLog.setPosition(sysUser.getUserJobTitle());
            interiorInquiryListLog.setOperation(InquiryOperationEnum.getName(InquiryOperationEnum.ADD_INQUIRY.getState()));
            interiorInquiryListLog.setOperationTime(System.currentTimeMillis());
            interiorInquiryListLog.setInquiryListId(inquiry.getId());
            interiorInquiryListLog.setDepartment(sysUser.getUserOrgName());
            interiorInquiryListLog.setCreateTime(System.currentTimeMillis());
            interiorInquiryListLog.setAuditOpinion("");
            inquiryInteriorRecordRepository.saveAndFlush(interiorInquiryListLog);

            countList(inquiry.getDetails(), sysUser.getMemberId(), sysUser.getMemberRoleId(), OperateDataSourceEnum.TRADE_COMMODITY_INQUIRY.getCode(), 1L, CommodityInquiryOperateTypeEnum.TO_BE_VALIFY_COMMIT.getCode(), 0l, 0);
            sendSystemMessage(inquiry, MessageTemplateCode.product_inquiry_wait_audit);
            return Wrapper.success(inquiry.getId());
        }else{
            return Wrapper.fail(result.getCode(), result.getMessage());
        }
    }

    /**
     * 交易中心-商品询价-待新增询价单详情
     * @author wrc
     * @date 2020/8/10
     */
    @Override
    public Wrapper<InquiryListDetailsResponse> inquiryListDetails(InquiryListDetailsRequest request, UserLoginCacheDTO sysUser) {
        InquiryListDetailsResponse inquiryDetailsResponse = new InquiryListDetailsResponse();
        Inquiry inquiry = inquiryRepository.findById(request.getId()).orElse(null);
        if (ObjectUtils.isEmpty(inquiry)) {
            return Wrapper.fail(ResponseCode.RECORDS_DON_T_EXIST);
        }
        BeanUtils.copyProperties(inquiry, inquiryDetailsResponse);
        inquiryDetailsResponse.setInquiryListMemberName(inquiry.getCreateMemberName());
        inquiryDetailsResponse.setInquiryListMemberId(inquiry.getCreateMemberId());
        inquiryDetailsResponse.setExternalStateName(InquiryExternalStatusEnum.getName(inquiry.getExternalState()));
        inquiryDetailsResponse.setInteriorStateName(InquiryInteriorStatusEnum.getName(inquiry.getInteriorState()));
        inquiryDetailsResponse.setVoucherTime(inquiry.getCreateTime());
        inquiryDetailsResponse.setMemberRoleId(inquiry.getMemberRoleId());
        inquiryDetailsResponse.setMemberName(inquiry.getMemberName());
        inquiryDetailsResponse.setMemberId(inquiry.getMemberId());
        inquiryDetailsResponse.setDeliveryTime(inquiry.getDeliveryTime());
        inquiryDetailsResponse.setCreateMemberName(inquiry.getCreateMemberName());
        inquiryDetailsResponse.setCreateMemberId(inquiry.getCreateMemberId());
        inquiryDetailsResponse.setEnclosureUrls(inquiry.getEnclosureUrls());
        inquiryDetailsResponse.setShopId(inquiry.getShopId());
        inquiryDetailsResponse.setContactId(inquiry.getContactId());
        inquiryDetailsResponse.setContactName(inquiry.getContactName());
        inquiryDetailsResponse.setPhoneCode(inquiry.getPhoneCode());
        inquiryDetailsResponse.setContactPhone(inquiry.getContactPhone());
        getInqyiryLog(inquiryDetailsResponse, inquiry.getId(), sysUser);
        getExternalLog(inquiryDetailsResponse, inquiry.getId(), sysUser);
        List<InquiryListProductResponse> collect = inquiryProductRepository.findAllByInquiryIdEquals(inquiry.getId()).stream().map(temp -> {
            InquiryListProductResponse inquiryProductResponse = new InquiryListProductResponse();
            BeanUtils.copyProperties(temp, inquiryProductResponse);
            inquiryProductResponse.setInquiryListId(temp.getInquiry() == null ? null : temp.getInquiry().getId());
            inquiryProductResponse.setProductQuotationId(temp.getQuote() == null ? null : temp.getQuote().getId());
            return inquiryProductResponse;
        }).collect(Collectors.toList());
        inquiryDetailsResponse.setInquiryListProductRequests(collect);
        return Wrapper.success(inquiryDetailsResponse);
    }

    /**
     * 交易中心-商品询价-待新增询价单删除
     * @author wrc
     * @date 2020/8/10
     */
    @Transactional
    @Override
    public Wrapper inquiryListDelete(InquiryListDetailsRequest request) {
        Optional<Inquiry> byId = inquiryRepository.findById(request.getId());
        if (!byId.isPresent()) {
            return Wrapper.fail(ResponseCode.RECORDS_DON_T_EXIST);
        }
        Inquiry inquiry = byId.get();
        //删除询价单，待提交审核且从未提交审核过的询价单才可以删除
        if (!OrderConstant.InteriorState.PENDING_REVIEW.equals(inquiry.getInteriorState())) {
            return Wrapper.fail(ResponseCode.PURCHASE_NOT_PRODUCT_INQUIRY_STATE_ERROR);
        }
        inquiryRepository.delete(inquiry);
        countList(inquiry.getDetails(), inquiry.getCreateMemberId(), inquiry.getCreateRoleId(), OperateDataSourceEnum.TRADE_COMMODITY_INQUIRY.getCode(), 0L, 0, 1L, CommodityInquiryOperateTypeEnum.TO_BE_VALIFY_COMMIT.getCode());
        return Wrapper.success();
    }

    /**
     * 报价单商品列表查询
     * @param request
     * @author wrc
     * @date 2020/11/9
     */
    @Override
    public Wrapper<PageData<InquiryListProductResponse>> inquiryDetails(InquiryListProductPageRequest request) {
        List<InquiryListProductResponse> list = new ArrayList<>();
        long count = 0;
        Page<InquiryProduct> inquiryProducts = inquiryProductRepository.findAllByQuoteIdEquals(request.getId(), PageRequest.of(request.getCurrent(), request.getPageSize()));
        if (null != inquiryProducts && inquiryProducts.getTotalElements() > 0) {
            count = inquiryProducts.getTotalElements();
            list = inquiryProducts.getContent().stream().map(temp -> {
                InquiryListProductResponse inquiryProductResponse = new InquiryListProductResponse();
                BeanUtils.copyProperties(temp, inquiryProductResponse);
                return inquiryProductResponse;
            }).collect(Collectors.toList());
        }
        return Wrapper.success(new PageData<>(count, list));
    }

    /**
     * 交易中心-商品询价-待新增询价单批量删除
     * @author wrc
     * @date 2020/8/11
     */
    @Transactional
    @Override
    public Wrapper inquiryListDeleteAll(InquiryListDeleteAllRequest request) {
        List<Inquiry> allById = inquiryRepository.findAllById(request.getIds());
        for (Inquiry inquiry : allById) {
            //删除询价单，待提交审核且从未提交审核过的询价单才可以删除
            if (!OrderConstant.InteriorState.PENDING_REVIEW.equals(inquiry.getInteriorState())) {
                return Wrapper.fail(ResponseCode.PURCHASE_CAN_NOT_DELETE);
            }
            countList(inquiry.getDetails(), inquiry.getCreateMemberId(), inquiry.getCreateRoleId(), OperateDataSourceEnum.TRADE_COMMODITY_INQUIRY.getCode(), 0L, 0, 1L, CommodityInquiryOperateTypeEnum.TO_BE_VALIFY_COMMIT.getCode());
        }
        inquiryRepository.deleteAll(allById);
        inquiryProductRepository.deleteAllByInquiryIdIn(request.getIds());
        return Wrapper.success();
    }

    /**
     * 交易中心-商品询价-待新增询价单修改
     * @author wrc
     * @date 2020/8/11
     */
    @Transactional
    @Override
    public Wrapper inquiryListUpdate(InquiryListUpdateRequest request, UserLoginCacheDTO sysUser) {
        Inquiry inquiry = inquiryRepository.findById(request.getId()).orElse(null);
        if (inquiry == null) {
            return Wrapper.fail(ResponseCode.RECORDS_DON_T_EXIST);
        }
        if(!(InquiryInteriorStatusEnum.TO_BE_SUBMITTED_FOR_REVIEW.getState().equals(inquiry.getInteriorState()) || InquiryInteriorStatusEnum.FAILED_TO_PASS_THE_AUDIT.getState().equals(inquiry.getInteriorState()) || InquiryInteriorStatusEnum.FAILED_TO_PASS_THE_AUDIT2.getState().equals(inquiry.getInteriorState()))) {
            return Wrapper.fail(ResponseCode.PURCHASE_CAN_NOT_UPDATE_BECAUSE_OF_STATUS_MISMATCH);
        }
//        //审核不通过、待提交审核状态的询价单都可以修改 修改后状态为待提交审核
//        if (!(OrderConstant.InteriorState.PENDING_REVIEW.equals(inquiry.getInteriorState()) || OrderConstant.InteriorState.NOT_APPROVED_PRODUCT.equals(inquiry.getInteriorState()))) {
//            return Wrapper.fail(ResponseCode.ORDER_NOT_PRODUCT_INQUIRY_STATE_ERROR);
//        }
        inquiry.setShopId(request.getShopId());
        inquiry.setContactId(request.getContactId());
        inquiry.setContactName(request.getContactName());
        inquiry.setPhoneCode(request.getPhoneCode());
        inquiry.setContactPhone(request.getContactPhone());
        inquiry.setTaxes(request.getTaxes());
        inquiry.setQuotationAsTime(request.getQuotationAsTime());
        inquiry.setPaymentType(request.getPaymentType());
        inquiry.setFullAddressId(request.getFullAddressId());
        inquiry.setFullAddress(request.getFullAddress());
        inquiry.setPackRequire(request.getPackRequire());
        inquiry.setOtherRequire(request.getOtherRequire());
        inquiry.setOffer(request.getOffer());
        inquiry.setLogistics(request.getLogistics());
        inquiry.setEnclosureUrls(request.getEnclosureUrls());
        inquiry.setDeliveryTime(request.getDeliveryTime());
        inquiry.setDetails(request.getDetails());
        inquiry.setUpdateTime(System.currentTimeMillis());
        inquiryProductRepository.deleteAllByInquiryIdEquals(inquiry.getId());

        //询价商品
        List<InquiryListProductRequest> inquiryProductRequests = request.getInquiryListProductRequests();
        HashMap<Long, CommodityGoodsResponse> commodityMap = new HashMap<>();
        List<Long> commoditySkuIdList = inquiryProductRequests.stream().map(InquiryListProductRequest::getProductId).collect(Collectors.toList());
        Wrapper<List<CommodityGoodsResponse>> result = commodityFeign.getCommodityByCommoditySkuIdList(commoditySkuIdList);
        if(ResponseCode.SUCCESS.getCode() == result.getCode()) {
            List<CommodityGoodsResponse> commodityGoodsResponseList = result.getData();
            commodityGoodsResponseList.forEach(commodityGoodsResponse -> commodityMap.put(commodityGoodsResponse.getId(), commodityGoodsResponse));

            List<String> memberList = new ArrayList<>();
            List<InquiryProduct> inquiryProductList = inquiryProductRequests.stream().map(inquiryProductRequest -> {
                CommodityGoodsResponse commodityGoodsResponse = commodityMap.get(inquiryProductRequest.getProductId());
                if(commodityGoodsResponse != null) {
                    Long upperCommoditySkuId = commodityGoodsResponse.getCommodityUnitPriceAndPicId();
                    Long upperMemberId = commodityGoodsResponse.getUpperMemberId();
                    String upperMemberName = commodityGoodsResponse.getUpperMemberName();
                    Long upperMemberRoleId = commodityGoodsResponse.getUpperMemberRoleId();
                    String upperMemberRoleName = commodityGoodsResponse.getUpperMemberRoleName();

                    //用来判断询价商品是否是同一个会员
                    if(upperCommoditySkuId != null && upperCommoditySkuId > 0){
                        String member = upperMemberId + "_" + upperMemberRoleId;
                        String upperMember = inquiry.getMemberId() + "_" + inquiry.getMemberRoleId();
                        if(!memberList.contains(member) && !upperMember.equals(member)){
                            memberList.add(member);
                        }
                    }

                    //税率
                    Double taxRate = commodityGoodsResponse.getTaxRate();

                    InquiryProduct inquiryProduct = new InquiryProduct();
                    inquiryProduct.setBrand(inquiryProductRequest.getBrand());
                    inquiryProduct.setPurchaseCount(inquiryProductRequest.getPurchaseCount());
                    inquiryProduct.setProductName(inquiryProductRequest.getProductName());
                    inquiryProduct.setProductId(inquiryProductRequest.getProductId());
                    inquiryProduct.setUnit(inquiryProductRequest.getUnit());
                    inquiryProduct.setCategory(inquiryProductRequest.getCategory());
                    inquiryProduct.setLogistics(inquiryProductRequest.getLogistics());
                    inquiryProduct.setCommodityId(inquiryProductRequest.getCommodityId());
                    inquiryProduct.setMemberId(inquiryProductRequest.getMemberId());
                    inquiryProduct.setMemberRoleId(inquiryProductRequest.getMemberRoleId());
                    inquiryProduct.setInquiry(inquiry);
                    inquiryProduct.setImgUrl(inquiryProductRequest.getImgUrl());
                    inquiryProduct.setTaxRate(taxRate);
                    inquiryProduct.setUpperCommoditySkuId(upperCommoditySkuId);
                    inquiryProduct.setUpperMemberId(upperMemberId);
                    inquiryProduct.setUpperMemberRoleId(upperMemberRoleId);
                    inquiryProduct.setUpperMemberName(upperMemberName);
                    inquiryProduct.setUpperMemberRoleName(upperMemberRoleName);
                    //商品销售区域
                    inquiryProduct.setIsAllArea(commodityGoodsResponse.getIsAllArea());
                    List<com.ssy.lingxi.product.api.model.response.commodity.CommodityAreaResponse> commodityAreaResponseList = commodityGoodsResponse.getCommodityAreaList();
                    if(!CollectionUtils.isEmpty(commodityAreaResponseList)) {
                        List<CommodityArea> commodityAreaList = commodityAreaResponseList.stream().map(commodityAreaResponse -> {
                            CommodityArea commodityArea = BeanUtil.copyProperties(commodityAreaResponse, CommodityArea.class);
                            commodityArea.setInquiryProduct(inquiryProduct);
                            return commodityArea;
                        }).collect(Collectors.toList());
                        inquiryProduct.setCommodityAreaList(commodityAreaList);
                    }
                    return inquiryProduct;
                }else{
                    throw new BusinessException(ResponseCode.PRODUCT_COMMODITY_NOT_EXIST);
                }
            }).collect(Collectors.toList());
            inquiry.setInquiryProductList(inquiryProductList);

            //根据被询价商品所属会员来判断是否可以进行二次询价
            int memberSize = memberList.size();
            if(memberSize > 0){
                inquiry.setIsSecondInquiry(memberSize == 1);
            }

            //启动流程
            TaskStartVO processStartVO = new TaskStartVO();
            processStartVO.setDataId(inquiry.getId());
            processStartVO.setRoleId(sysUser.getMemberRoleId());
            processStartVO.setMemberId(sysUser.getMemberId());
            processStartVO.setProcessKey(ProcessEnum.TRADE_INQUIRY_INNER.getProcessKey());
            Wrapper<SimpleTaskCompleteVO> taskResultVOWrapper = processFeign.startSimpleProcess(processStartVO);
            if (ResponseCode.SUCCESS.getCode() != taskResultVOWrapper.getCode()) {
                throw new RuntimeException(taskResultVOWrapper.getMessage());
            }
            inquiry.setInteriorTaskId(taskResultVOWrapper.getData().getTaskId());
            inquiry.setInteriorState(taskResultVOWrapper.getData().getStatus());
            inquiryRepository.saveAndFlush(inquiry);

            //记录日志
            InquiryInteriorRecord interiorInquiryListLog = new InquiryInteriorRecord();
            interiorInquiryListLog.setCreateRoleId(sysUser.getMemberRoleId());
            interiorInquiryListLog.setUpdateTime(System.currentTimeMillis());
            interiorInquiryListLog.setState(taskResultVOWrapper.getData().getStatus());
            interiorInquiryListLog.setRoleName(sysUser.getUserName());
            interiorInquiryListLog.setRoleId(sysUser.getMemberRoleId());
            interiorInquiryListLog.setPosition(sysUser.getUserJobTitle());
            interiorInquiryListLog.setOperation(InquiryOperationEnum.getName(InquiryOperationEnum.UPDATE_INQUIRY.getState()));
            interiorInquiryListLog.setOperationTime(System.currentTimeMillis());
            interiorInquiryListLog.setInquiryListId(inquiry.getId());
            interiorInquiryListLog.setDepartment(sysUser.getUserOrgName());
            interiorInquiryListLog.setCreateTime(System.currentTimeMillis());
            interiorInquiryListLog.setAuditOpinion("");
            inquiryInteriorRecordRepository.save(interiorInquiryListLog);

            return Wrapper.success();
        }else{
            return Wrapper.fail(result.getCode(), result.getMessage());
        }
    }

    /**
     * 交易中心-商品询价-询价商品列表查询
     * @author wrc
     * @date 2020/8/11
     */
    @Override
    public Wrapper<PageData<InquiryListProductResponse>> enquiryProductList(EnquiryProductListRequest request) {
        long count = 0L;
        List<InquiryListProductResponse> list = new ArrayList<>();
        PageRequest page = PageRequest.of(request.getCurrent(), request.getPageSize(), Sort.by("id").ascending());
        Page<InquiryProduct> inquiryProducts = inquiryProductRepository.findByInquiryId(request.getId(), page);
        if (inquiryProducts.getTotalElements() > 0) {
            count = inquiryProducts.getTotalElements();
            list = inquiryProducts.getContent().stream().map(temp -> {
                InquiryListProductResponse product = new InquiryListProductResponse();
                BeanUtils.copyProperties(temp, product);
                product.setPrice(temp.getPrice());
                product.setMoney(temp.getMoney());
                product.setCommodityId(temp.getCommodityId());
                product.setImgUrl(temp.getImgUrl());
                return product;
            }).collect(Collectors.toList());
        }
        return Wrapper.success(new PageData<>(count, list));
    }

    /**
     * 交易中心-商品询价-询价商品列表查询
     * @author wrc
     * @date 2020/8/11
     */
    @Override
    public Wrapper<List<InquiryListProductResponse>> enquiryProductAll(EnquiryProductListRequest request, UserLoginCacheDTO sysUser) {
        Inquiry inquiry = inquiryRepository.findById(request.getId()).orElse(null);
        if (null == inquiry) {
            return Wrapper.fail(ResponseCode.RECORDS_DON_T_EXIST);
        }
        Long shopId = inquiry.getShopId();
        List<InquiryListProductResponse> list = new ArrayList<>();
        List<InquiryProduct> all = inquiryProductRepository.findAllByInquiryIdEquals(request.getId());
        if (all.size() > 0) {

            //组装redis键值格式
            List<HashMap<String, String[]>> keyFieldList = all.stream().map(inquiryProduct -> {
                HashMap<String, String[]> map = new HashMap<>();
                String unitPriceAndPicId = CommonConstant.FREIGHT_SPACE_REDIS_KEY + shopId + "_" + inquiryProduct.getProductId();
                String commodityMemberId = String.valueOf(sysUser.getMemberId());
                map.put(unitPriceAndPicId, new String[]{commodityMemberId, CommonConstant.FREIGHT_All});
                return map;
            }).collect(Collectors.toList());

            //获取库存数据
            List<Object> resultList = redisStringUtils.hMGetBatch(keyFieldList, Constants.REDIS_PRODUCT_INDEX);
            for(int i = 0; i < all.size(); i++){
                InquiryProduct temp = all.get(i);
                InquiryListProductResponse product = new InquiryListProductResponse();
                BeanUtils.copyProperties(temp, product);
                product.setPurchaseCount(temp.getPurchaseCount());
                product.setCategory(temp.getCategory());
                product.setUnit(temp.getUnit());
                product.setLogistics(temp.getLogistics());
                product.setPrice(temp.getPrice());
                product.setMemberId(temp.getMemberId());
                product.setMemberRoleId(temp.getMemberRoleId());
                product.setMinOrder(temp.getMinOrder());
                product.setImgUrl(temp.getImgUrl());
                product.setMemberName(inquiry.getMemberName());
                product.setTaxRate(temp.getTaxRate());
                product.setIsAllArea(temp.getIsAllArea());
                //销售区域
                List<CommodityArea> commodityAreaList = temp.getCommodityAreaList();
                List<CommodityAreaResponse> commodityAreaResponseList = commodityAreaList.stream().map(commodityArea -> BeanUtil.copyProperties(commodityArea, CommodityAreaResponse.class)).collect(Collectors.toList());
                product.setCommodityAreaList(commodityAreaResponseList);

                //计算当前商品的库存数
                List<String> stockList = (List<String>)resultList.get(i);
                if(stockList != null && !stockList.isEmpty()){
                    List<String> collect = stockList.stream().filter(StrUtil::isNotEmpty).collect(Collectors.toList());
                    if(!collect.isEmpty()){
                        Double stockCount = collect.stream().map(Double::parseDouble).reduce(Double::sum).get();
                        product.setStockCount(stockCount);
                    }
                }

                list.add(product);
            }
        }
        return Wrapper.success(list);
    }

    /**
     * 商品询价-待新增提交审核
     * @author wrc
     * @date 2020/8/11
     */
    @Transactional
    @Override
    public Wrapper inquiryListSubmit(InquiryListSubmitRequest request, UserLoginCacheDTO sysUser) {
        Inquiry inquiry = inquiryRepository.findById(request.getId()).orElse(null);
        if (inquiry == null) {
            return Wrapper.fail(ResponseCode.RECORDS_DON_T_EXIST);
        }
        Wrapper wrapper = auditInterior(inquiry, request.getAuditOpinion(), OrderConstant.InteriorStatus.STATE_DEFAULT, sysUser, InquiryOperationEnum.getName(InquiryOperationEnum.SUBMIT_CHECK_INQUIRY.getState()));
        countList(inquiry.getDetails(), sysUser.getMemberId(), sysUser.getMemberRoleId(), OperateDataSourceEnum.TRADE_COMMODITY_INQUIRY.getCode(), 1L, CommodityInquiryOperateTypeEnum.TO_BE_VALIFY_STEP1.getCode(), 1L, CommodityInquiryOperateTypeEnum.TO_BE_VALIFY_COMMIT.getCode());
        sendSystemMessage(inquiry, MessageTemplateCode.product_inquiry_audit_step_1);
        return wrapper;
    }

    /**
     * 交易中心-商品询价-待新增批量提交审核
     * @author wrc
     * @date 2020/8/11
     */
    @Override
    public Wrapper inquiryListSubmitAll(InquiryListSubmitAllRequest request, UserLoginCacheDTO sysUser) {
        List<Inquiry> allById = inquiryRepository.findAllById(request.getIds());
        if (CollectionUtils.isEmpty(allById)) {
            return Wrapper.fail(ResponseCode.RECORDS_DON_T_EXIST);
        }
        Wrapper wrapper = auditInteriorAll(allById, OrderConstant.InteriorStatus.STATE_DEFAULT, sysUser, InquiryOperationEnum.getName(InquiryOperationEnum.SUBMIT_CHECK_INQUIRY.getState()));
        allById.forEach(inquiry -> {
            countList(inquiry.getDetails(), sysUser.getMemberId(), sysUser.getMemberRoleId(), OperateDataSourceEnum.TRADE_COMMODITY_INQUIRY.getCode(), 1L, CommodityInquiryOperateTypeEnum.TO_BE_VALIFY_STEP1.getCode(), 1L, CommodityInquiryOperateTypeEnum.TO_BE_VALIFY_COMMIT.getCode());
        });
        batchSendSystemMessage(allById, MessageTemplateCode.product_inquiry_audit_step_1);
        return wrapper;
    }

    /**
     * 交易能力 商品询价 待审核询价单一级列表查询
     * @author wrc
     * @date 2020/8/11
     */
    @Override
    public Wrapper<PageData<InquiryListResponse>> inquiryToAuditList(InquiryListRequest request, UserLoginCacheDTO sysUser) {
        Pageable page = PageRequest.of(request.getCurrent(), request.getPageSize());
        Page<Inquiry> result = inquiryRepository.findAll(getSpecification(request, sysUser.getMemberId(), sysUser.getMemberRoleId(), null, null, OrderConstant.InquiryQueryType.INQUIRY_CHECK_ONE), page);
        List<InquiryListResponse> inquiryListResponseList = result.getContent().stream().map(inquiry -> {
            InquiryListResponse inquiryListResponse = BeanUtil.copyProperties(inquiry, InquiryListResponse.class);
            inquiryListResponse.setExternalStateName(InquiryExternalStatusEnum.getName(inquiryListResponse.getExternalState()));
            inquiryListResponse.setInteriorStateName(InquiryInteriorStatusEnum.getName(inquiryListResponse.getInteriorState()));
            inquiryListResponse.setInquiryListMemberName(inquiry.getCreateMemberName());
            inquiryListResponse.setInquiryListMemberId(inquiry.getCreateMemberId());
            List<InquiryProduct> inquiryProductList = inquiry.getInquiryProductList();
            if(!CollectionUtils.isEmpty(inquiryProductList)){
                inquiryListResponse.setImgUrl(inquiryProductList.get(0).getImgUrl());
            }
            return inquiryListResponse;
        }).collect(Collectors.toList());
        return Wrapper.success(new PageData<>(result.getTotalElements(), inquiryListResponseList));
    }

    /**
     * 交易能力 商品询价 待审核询价单（一级）单据审核
     * @author wrc
     * @date 2020/8/12
     */
    @Override
    public Wrapper inquiryDocumentsReview(InquiryListSubmitRequest request, UserLoginCacheDTO sysUser) {
        Optional<Inquiry> byId = inquiryRepository.findById(request.getId());
        if (!byId.isPresent()) {
            return Wrapper.fail(ResponseCode.RECORDS_DON_T_EXIST);
        }
        Inquiry inquiry = byId.get();
        Wrapper wrapper = auditInterior(inquiry, request.getAuditOpinion(), request.getState(), sysUser, InquiryOperationEnum.getName(InquiryOperationEnum.CHECK_INQUIRY_1.getState()));
        if (OrderConstant.State.START.equals(request.getState())) {
            countList(inquiry.getDetails(), sysUser.getMemberId(), sysUser.getMemberRoleId(), OperateDataSourceEnum.TRADE_COMMODITY_INQUIRY.getCode(), 1L, CommodityInquiryOperateTypeEnum.TO_BE_VALIFY_STEP2.getCode(), 1L, CommodityInquiryOperateTypeEnum.TO_BE_VALIFY_STEP1.getCode());
            sendSystemMessage(inquiry, MessageTemplateCode.product_inquiry_audit_step_2);
        } else {
            countList(inquiry.getDetails(), sysUser.getMemberId(), sysUser.getMemberRoleId(), OperateDataSourceEnum.TRADE_COMMODITY_INQUIRY.getCode(), 1L, CommodityInquiryOperateTypeEnum.TO_BE_VALIFY_COMMIT.getCode(), 1L, CommodityInquiryOperateTypeEnum.TO_BE_VALIFY_STEP1.getCode());
            sendSystemMessage(inquiry, MessageTemplateCode.product_inquiry_wait_audit);
        }
        return wrapper;
    }

    /**
     * 交易能力 商品询价 待审核询价单（一级）单据审核 批量
     * @author wrc
     * @date 2020/8/12
     */
    @Override
    public Wrapper inquiryDocumentsReviewAll(InquiryListSubmitAllRequest request, UserLoginCacheDTO sysUser) {
        List<Inquiry> allById = inquiryRepository.findAllById(request.getIds());
        if (CollectionUtils.isEmpty(allById)) {
            return Wrapper.fail(ResponseCode.RECORDS_DON_T_EXIST);
        }
        allById.forEach(inquiry -> {
            countList(inquiry.getDetails(), sysUser.getMemberId(), sysUser.getMemberRoleId(), OperateDataSourceEnum.TRADE_COMMODITY_INQUIRY.getCode(), 1L, CommodityInquiryOperateTypeEnum.TO_BE_VALIFY_STEP2.getCode(), 1L, CommodityInquiryOperateTypeEnum.TO_BE_VALIFY_STEP1.getCode());
        });
        batchSendSystemMessage(allById, MessageTemplateCode.product_inquiry_audit_step_2);
        return auditInteriorAll(allById, OrderConstant.InteriorStatus.STATE_PASS, sysUser, InquiryOperationEnum.getName(InquiryOperationEnum.CHECK_INQUIRY_1.getState()));
    }

    /**
     * 交易能力 商品询价 待审核询价单二级列表查询
     * @author wrc
     * @date 2020/8/11
     */
    @Override
    public Wrapper<PageData<InquiryListResponse>> inquiryToAuditListTwo(InquiryListRequest request, UserLoginCacheDTO sysUser) {
        Pageable page = PageRequest.of(request.getCurrent(), request.getPageSize());
        Page<Inquiry> result = inquiryRepository.findAll(getSpecification(request, sysUser.getMemberId(), sysUser.getMemberRoleId(), null, null, OrderConstant.InquiryQueryType.INQUIRY_CHECK_TWO), page);
        List<InquiryListResponse> inquiryListResponseList = result.getContent().stream().map(inquiry -> {
            InquiryListResponse inquiryListResponse = BeanUtil.copyProperties(inquiry, InquiryListResponse.class);
            inquiryListResponse.setExternalStateName(InquiryExternalStatusEnum.getName(inquiryListResponse.getExternalState()));
            inquiryListResponse.setInteriorStateName(InquiryInteriorStatusEnum.getName(inquiryListResponse.getInteriorState()));
            inquiryListResponse.setInquiryListMemberName(inquiry.getCreateMemberName());
            inquiryListResponse.setInquiryListMemberId(inquiry.getCreateMemberId());
            List<InquiryProduct> inquiryProductList = inquiry.getInquiryProductList();
            if(!CollectionUtils.isEmpty(inquiryProductList)){
                inquiryListResponse.setImgUrl(inquiryProductList.get(0).getImgUrl());
            }
            return inquiryListResponse;
        }).collect(Collectors.toList());
        return Wrapper.success(new PageData<>(result.getTotalElements(), inquiryListResponseList));
    }

    /**
     * 交易能力 商品询价 待审核询价单（二级）单据审核
     * @author wrc
     * @date 2020/8/12
     */
    @Override
    public Wrapper inquiryDocumentsReviewTwo(InquiryListSubmitRequest request, UserLoginCacheDTO sysUser) {
        Optional<Inquiry> byId = inquiryRepository.findById(request.getId());
        if (!byId.isPresent()) {
            return Wrapper.fail(ResponseCode.RECORDS_DON_T_EXIST);
        }
        Inquiry inquiry = byId.get();
        if (OrderConstant.State.START.equals(request.getState())) {
            countList(inquiry.getDetails(), sysUser.getMemberId(), sysUser.getMemberRoleId(), OperateDataSourceEnum.TRADE_COMMODITY_INQUIRY.getCode(), 1L, CommodityInquiryOperateTypeEnum.TO_BE_COMMIT.getCode(), 1L, CommodityInquiryOperateTypeEnum.TO_BE_VALIFY_STEP2.getCode());
            sendSystemMessage(inquiry, MessageTemplateCode.product_inquiry_submit);
        } else {
            countList(inquiry.getDetails(), sysUser.getMemberId(), sysUser.getMemberRoleId(), OperateDataSourceEnum.TRADE_COMMODITY_INQUIRY.getCode(), 1L, CommodityInquiryOperateTypeEnum.TO_BE_VALIFY_COMMIT.getCode(), 1L, CommodityInquiryOperateTypeEnum.TO_BE_VALIFY_STEP2.getCode());
            sendSystemMessage(inquiry, MessageTemplateCode.product_inquiry_wait_audit);
        }

        return auditInterior(inquiry, request.getAuditOpinion(), request.getState(), sysUser, InquiryOperationEnum.getName(InquiryOperationEnum.CHECK_INQUIRY_2.getState()));
    }

    /**
     * 交易能力 商品询价 待审核询价单（二级）单据审核 批量
     * @author wrc
     * @date 2020/8/12
     */
    @Override
    public Wrapper inquiryDocumentsReviewAllTwo(InquiryListSubmitAllRequest request, UserLoginCacheDTO sysUser) {
        List<Inquiry> allById = inquiryRepository.findAllById(request.getIds());
        if (CollectionUtils.isEmpty(allById)) {
            return Wrapper.fail(ResponseCode.RECORDS_DON_T_EXIST);
        }
        batchSendSystemMessage(allById, MessageTemplateCode.product_inquiry_submit);
        allById.forEach(inquiry -> {
            countList(inquiry.getDetails(), sysUser.getMemberId(), sysUser.getMemberRoleId(), OperateDataSourceEnum.TRADE_COMMODITY_INQUIRY.getCode(), 1L, CommodityInquiryOperateTypeEnum.TO_BE_COMMIT.getCode(), 1L, CommodityInquiryOperateTypeEnum.TO_BE_VALIFY_STEP2.getCode());
        });
        return auditInteriorAll(allById, OrderConstant.InteriorStatus.STATE_PASS, sysUser, InquiryOperationEnum.getName(InquiryOperationEnum.CHECK_INQUIRY_2.getState()));
    }

    /**
     * 交易能力 商品询价 待提交询价单列表查询
     * @author wrc
     * @date 2020/8/12
     */
    @Override
    public Wrapper<PageData<InquiryListResponse>> submitInquirySheetList(InquiryListRequest request, UserLoginCacheDTO sysUser) {
        Pageable page = PageRequest.of(request.getCurrent(), request.getPageSize());
        Page<Inquiry> result = inquiryRepository.findAll(getSpecification(request, sysUser.getMemberId(), sysUser.getMemberRoleId(), null, null, OrderConstant.InquiryQueryType.INQUIRY_NOT_CONFIRM), page);
        List<InquiryListResponse> inquiryListResponseList = result.getContent().stream().map(inquiry -> {
            InquiryListResponse inquiryListResponse = BeanUtil.copyProperties(inquiry, InquiryListResponse.class);
            inquiryListResponse.setExternalStateName(InquiryExternalStatusEnum.getName(inquiryListResponse.getExternalState()));
            inquiryListResponse.setInteriorStateName(InquiryInteriorStatusEnum.getName(inquiryListResponse.getInteriorState()));
            inquiryListResponse.setInquiryListMemberName(inquiry.getCreateMemberName());
            inquiryListResponse.setInquiryListMemberId(inquiry.getCreateMemberId());
            List<InquiryProduct> inquiryProductList = inquiry.getInquiryProductList();
            if(!CollectionUtils.isEmpty(inquiryProductList)){
                inquiryListResponse.setImgUrl(inquiryProductList.get(0).getImgUrl());
            }
            return inquiryListResponse;
        }).collect(Collectors.toList());
        return Wrapper.success(new PageData<>(result.getTotalElements(), inquiryListResponseList));
    }

    /**
     * 交易能力 商品询价 提交询价单
     * @author wrc
     * @date 2020/8/12
     */
    @Override
    public Wrapper inquirySubmit(InquiryListSubmitRequest request, UserLoginCacheDTO sysUser) {
        Optional<Inquiry> byId = inquiryRepository.findById(request.getId());
        if (!byId.isPresent()) {
            return Wrapper.fail(ResponseCode.RECORDS_DON_T_EXIST);
        }
        Inquiry inquiry = byId.get();
        Wrapper wrapper = auditInterior(inquiry, null, OrderConstant.Auditing.DEFAULT, sysUser, InquiryOperationEnum.getName(InquiryOperationEnum.SUBMIT_INQUIRY.getState()));
        if (ResponseCode.SUCCESS.getCode() != wrapper.getCode()) {
            return wrapper;
        }
        //执行外部工作流程
        Wrapper wrapperExternal = auditExternal(inquiry, request.getAuditOpinion(), OrderConstant.Auditing.DEFAULT, sysUser, InquiryOperationEnum.getName(InquiryOperationEnum.SUBMIT_INQUIRY.getState()));
        countList(inquiry.getDetails(), sysUser.getMemberId(), sysUser.getMemberRoleId(), OperateDataSourceEnum.TRADE_COMMODITY_INQUIRY.getCode(), 0l, 0, 1L, CommodityInquiryOperateTypeEnum.TO_BE_COMMIT.getCode());
        return wrapperExternal;
    }

    /**
     * 交易能力 商品询价 提交询价单 批量
     * @author wrc
     * @date 2020/8/12
     */
    @Override
    public Wrapper inquirySubmitAll(InquiryListSubmitAllRequest request, UserLoginCacheDTO sysUser) {
        List<Inquiry> allById = inquiryRepository.findAllById(request.getIds());
        if (CollectionUtils.isEmpty(allById)) {
            return Wrapper.fail(ResponseCode.RECORDS_DON_T_EXIST);
        }
        Wrapper wrapper = auditInteriorAll(allById, OrderConstant.Auditing.DEFAULT, sysUser, InquiryOperationEnum.getName(InquiryOperationEnum.SUBMIT_INQUIRY.getState()));
        if (ResponseCode.SUCCESS.getCode() != wrapper.getCode()) {
            return wrapper;
        }
        List<InquiryExternalRecord> list = new ArrayList<>();
        //执行外部工作流程
        for (Inquiry inquiry : allById) {
            TaskExecuteVO processStartVO = new TaskExecuteVO();
            processStartVO.setRoleId(sysUser.getMemberRoleId());
            processStartVO.setAgree(OrderConstant.Auditing.DEFAULT);
            processStartVO.setTaskId(inquiry.getExternalTaskId());
            processStartVO.setMemberId(sysUser.getMemberId());
            processStartVO.setProcessKey(ProcessEnum.TRADE_INQUIRY_EXTERNAL.getProcessKey());
            processStartVO.setDataId(inquiry.getId());
            Wrapper<SimpleTaskCompleteVO> taskResultVOWrapper = processFeign.completeSimpleTask(processStartVO);
            if (ResponseCode.SUCCESS.getCode() == taskResultVOWrapper.getCode()) {
                inquiry.setExternalTaskId(taskResultVOWrapper.getData().getTaskId());
                inquiry.setExternalState(taskResultVOWrapper.getData().getStatus());
                inquiry.setUpdateTime(System.currentTimeMillis());
                inquiryRepository.save(inquiry);
                InquiryExternalRecord externalInquiryListLogInquiryListLog = new InquiryExternalRecord();
                externalInquiryListLogInquiryListLog.setCreateRoleId(sysUser.getUserId());
                externalInquiryListLogInquiryListLog.setRoleId(sysUser.getMemberRoleId());
                externalInquiryListLogInquiryListLog.setCreateTime(System.currentTimeMillis());
                externalInquiryListLogInquiryListLog.setState(taskResultVOWrapper.getData().getStatus());
                externalInquiryListLogInquiryListLog.setRoleName(sysUser.getMemberRoleName());
                externalInquiryListLogInquiryListLog.setOperationTime(System.currentTimeMillis());
                externalInquiryListLogInquiryListLog.setOperation(InquiryOperationEnum.getName(InquiryOperationEnum.SUBMIT_INQUIRY.getState()));
                externalInquiryListLogInquiryListLog.setRoleName(sysUser.getMemberRoleName());
                externalInquiryListLogInquiryListLog.setInquiryListId(inquiry.getId());
                externalInquiryListLogInquiryListLog.setAuditOpinion("");
                list.add(externalInquiryListLogInquiryListLog);
            }
            countList(inquiry.getDetails(), sysUser.getMemberId(), sysUser.getMemberRoleId(), OperateDataSourceEnum.TRADE_COMMODITY_INQUIRY.getCode(), 0L, 0, 1L, CommodityInquiryOperateTypeEnum.TO_BE_COMMIT.getCode());
            sendSystemMessage(inquiry, MessageTemplateCode.inquiry_quotation_wait_submit);
        }
        if (!CollectionUtils.isEmpty(list)) {
            inquiryExternalRecordRepository.saveAll(list);
        }
        return Wrapper.success();
    }

    /**
     * 商品询价-查询上游供应会员和商品
     */
    @Override
    public Wrapper<InquiryUpperMemberCommodityResponse> getUpperMemberCommodity(Long inquiryId) {
        InquiryUpperMemberCommodityResponse inquiryUpperMemberCommodity = new InquiryUpperMemberCommodityResponse();
        List<Long> commoditySkuIdList = new ArrayList<>();
        List<String> upperMemberList = new ArrayList<>();
        HashMap<Long, Double> purchaseCountMap = new HashMap<>();
        List<InquiryProduct> inquiryProductList = inquiryProductRepository.findAllByInquiryIdEquals(inquiryId);
        for (InquiryProduct inquiryProduct : inquiryProductList) {
            //判断是否出现多会员商品
            Long upperCommoditySkuId = inquiryProduct.getUpperCommoditySkuId();
            if(upperCommoditySkuId != null && upperCommoditySkuId > 0){
                Long upperMemberId = inquiryProduct.getUpperMemberId();
                String upperMemberName = inquiryProduct.getUpperMemberName();
                Long upperMemberRoleId = inquiryProduct.getUpperMemberRoleId();
                String upperMemberRoleName = inquiryProduct.getUpperMemberRoleName();

                String member = upperMemberId + "_" + upperMemberRoleId;
                if (upperMemberList.size() == 0) {
                    inquiryUpperMemberCommodity.setMemberId(upperMemberId);
                    inquiryUpperMemberCommodity.setMemberName(upperMemberName);
                    inquiryUpperMemberCommodity.setMemberRoleId(upperMemberRoleId);
                    inquiryUpperMemberCommodity.setMemberRoleName(upperMemberRoleName);
                    upperMemberList.add(member);
                }else{
                    if(!upperMemberList.contains(member)){
                        throw new BusinessException(ResponseCode.PURCHASE_INQUIRY_COMMODITIES_DUPLICATED);
                    }
                }

                commoditySkuIdList.add(inquiryProduct.getUpperCommoditySkuId());
                //记录每个商品的采购数量
                purchaseCountMap.put(upperCommoditySkuId, inquiryProduct.getPurchaseCount());
            }
        }

        if(commoditySkuIdList.size() > 0){
            Wrapper<List<CommodityGoodsResponse>> result = commodityFeign.getCommodityByCommoditySkuIdList(commoditySkuIdList);
            if (ResponseCode.SUCCESS.getCode() == result.getCode()) {
                List<CommodityGoodsResponse> commodityGoodsResponseList = result.getData();
                if(commodityGoodsResponseList != null && commodityGoodsResponseList.size() > 0){
                    List<UpperCommodityResponse> upperCommodityResponseList = commodityGoodsResponseList.stream().map(commodityGoodsResponse -> {
                        UpperCommodityResponse upperCommodityResponse = BeanUtil.copyProperties(commodityGoodsResponse, UpperCommodityResponse.class);
                        upperCommodityResponse.setPurchaseCount(purchaseCountMap.get(commodityGoodsResponse.getId()));
                        return upperCommodityResponse;
                    }).collect(Collectors.toList());
                    inquiryUpperMemberCommodity.setCommodityList(upperCommodityResponseList);
                }
            }
        }

        return Wrapper.success(inquiryUpperMemberCommodity);
    }

    /**
     * 内部工作流程枚举
     * @author wrc
     * @date 2020/7/28
     */
    @Override
    public Wrapper<List<QuotationExternalStateEnumResponse>> getProductInquiryInteriorEnum(QuotationExternalStateEnumRequest request) {
        return Wrapper.success(Arrays.stream(InquiryInteriorStatusEnum.values()).map(r -> {
            QuotationExternalStateEnumResponse status = new QuotationExternalStateEnumResponse();
            status.setState(r.getState());
            status.setName(r.getName());
            return status;
        }).collect(Collectors.toList()));
    }

    /**
     * 外部工作流程枚举
     * @author wrc
     * @date 2020/11/23
     */
    @Override
    public Wrapper<List<QuotationExternalStateEnumResponse>> getProductexternalInteriorEnum() {
        return Wrapper.success(Arrays.stream(InquiryExternalStatusEnum.values()).map(r -> {
            QuotationExternalStateEnumResponse status = new QuotationExternalStateEnumResponse();
            status.setState(r.getState());
            status.setName(r.getName());
            return status;
        }).collect(Collectors.toList()));
    }

    /**
     * 积分同步
     */
    @Transactional
    @Override
    public Wrapper memberInquiryIntegralUpdate(MemberInquiryIntegralUpdateRequest request) {
        List<Inquiry> inquirys = inquiryRepository.findAllByCreateMemberIdAndCreateRoleId(request.getMemberId(), request.getMemberRoleId());
        if (!CollectionUtils.isEmpty(inquirys)) {
            inquirys.forEach(v -> {
                v.setIntegral(request.getIntegral());
            });
            inquiryRepository.saveAll(inquirys);
        }
        return Wrapper.success();
    }

    /**
     * 商城能力--企业商城-商品询价动态
     */
    @Override
    public Wrapper<PageData<ShopInquiryListResponse>> getShopInquiryList(PageVO pageVO, Long shopId) {
        Sort sort = Sort.by("voucherTime").descending();
        Pageable page = PageRequest.of(pageVO.getCurrent() - 1, pageVO.getPageSize(), sort);

        Page<Inquiry> result = inquiryRepository.findByShopIdAndInteriorState(shopId, InquiryInteriorStatusEnum.APPROVED_TWO.getState(), page);
        List<Inquiry> inquiryList = result.getContent();
        if(inquiryList.size() > 0){
            List<ShopInquiryListResponse> shopInquiryListResponseList = inquiryList.stream().map(inquiry -> {
                Long inquiryId = inquiry.getId();
                Integer externalState = inquiry.getExternalState();
                ShopInquiryListResponse shopInquiryListResponse = BeanUtil.copyProperties(inquiry, ShopInquiryListResponse.class);
                if(InquiryExternalStatusEnum.ACCEPT_OFFER.getState().equals(externalState) || InquiryExternalStatusEnum.OFFER_NOT_ACCEPTED.getState().equals(externalState)){
                    shopInquiryListResponse.setIsFinish(true);
                }
                InquiryProduct inquiryProduct = inquiryProductRepository.findFirstByInquiryId(inquiryId);
                if(inquiryProduct != null){
                    shopInquiryListResponse.setInquiryCommodityId(inquiryProduct.getCommodityId());
                }
                return shopInquiryListResponse;
            }).collect(Collectors.toList());
            return Wrapper.success(new PageData<>(result.getTotalElements(), shopInquiryListResponseList));
        }else{
            return Wrapper.success(new PageData<>(0L, new ArrayList<>()));
        }
    }

    /**
     * 商城能力--企业商城&渠道商城共用--店铺-询价商品详情-接口
     */
    @Override
    public Wrapper<InquiryListProductResponse> inquiryProductDetails(BaseDetailsRequest request, UserLoginCacheDTO sysUser) {
        InquiryListProductResponse response = new InquiryListProductResponse();
        InquiryProduct inquiryProduct = inquiryProductRepository.findById(request.getId()).orElse(null);
        if (!ObjectUtils.isEmpty(inquiryProduct)) {
            BeanUtils.copyProperties(inquiryProduct, response);
        }
        return Wrapper.success(response);
    }

    /**
     * 工作流内部审核
     * @param: cause 审核原因, state 审核状态1.通过 0.不通过 -1, inquiry：商品询价单
     * @return 执行工作流结果
     * @author wrc
     * 2020/8/11 17:23
     */
    private Wrapper auditInterior(Inquiry inquiry, String cause, Integer state, UserLoginCacheDTO sysUser, String operation) {
        //添加需求报价单内部流转记录
        TaskExecuteVO processStartVO = new TaskExecuteVO();
        processStartVO.setRoleId(sysUser.getMemberRoleId());
        processStartVO.setAgree(state);
        processStartVO.setTaskId(inquiry.getInteriorTaskId());
        processStartVO.setMemberId(sysUser.getMemberId());
        processStartVO.setProcessKey(ProcessEnum.TRADE_INQUIRY_INNER.getProcessKey());
        processStartVO.setDataId(inquiry.getId());
        Wrapper<SimpleTaskCompleteVO> taskResultVOWrapper = processFeign.completeSimpleTask(processStartVO);
        if (ResponseCode.SUCCESS.getCode() == taskResultVOWrapper.getCode()) {
            inquiry.setInteriorTaskId(taskResultVOWrapper.getData().getTaskId());
            inquiry.setInteriorState(taskResultVOWrapper.getData().getStatus());
            inquiry.setUpdateTime(System.currentTimeMillis());
            inquiryRepository.save(inquiry);
            InquiryInteriorRecord interiorInquiryListLog = new InquiryInteriorRecord();
            interiorInquiryListLog.setCreateRoleId(sysUser.getMemberRoleId());
            interiorInquiryListLog.setRoleId(sysUser.getMemberRoleId());
            interiorInquiryListLog.setCreateTime(System.currentTimeMillis());
            interiorInquiryListLog.setDepartment(sysUser.getUserOrgName());
            interiorInquiryListLog.setState(taskResultVOWrapper.getData().getStatus());
            interiorInquiryListLog.setRoleName(sysUser.getUserName());
            interiorInquiryListLog.setPosition(sysUser.getUserJobTitle());
            interiorInquiryListLog.setOperationTime(System.currentTimeMillis());
            interiorInquiryListLog.setOperation(operation);
            interiorInquiryListLog.setInquiryListId(inquiry.getId());
            interiorInquiryListLog.setAuditOpinion(cause);
            inquiryInteriorRecordRepository.save(interiorInquiryListLog);
        }
        return taskResultVOWrapper;
    }

    /**
     * 工作流外部部审核
     * @param: cause 审核原因, state 审核状态1.通过 0.不通过 -1, inquiry：商品询价单
     * @return 执行工作流结果
     * @author wrc
     * 2020/8/11 17:23
     */
    private Wrapper auditExternal(Inquiry inquiry, String cause, Integer state, UserLoginCacheDTO sysUser, String operation) {
        //添加需求报价单内部流转记录
        TaskExecuteVO processStartVO = new TaskExecuteVO();
        processStartVO.setRoleId(sysUser.getMemberRoleId());
        processStartVO.setAgree(state);
        processStartVO.setTaskId(inquiry.getExternalTaskId());
        processStartVO.setMemberId(sysUser.getMemberId());
        processStartVO.setProcessKey(ProcessEnum.TRADE_INQUIRY_EXTERNAL.getProcessKey());
        processStartVO.setDataId(inquiry.getId());
        Wrapper<SimpleTaskCompleteVO> taskResultVOWrapper = processFeign.completeSimpleTask(processStartVO);
        if (ResponseCode.SUCCESS.getCode() == taskResultVOWrapper.getCode()) {
            inquiry.setExternalTaskId(taskResultVOWrapper.getData().getTaskId());
            inquiry.setExternalState(taskResultVOWrapper.getData().getStatus());
            inquiry.setUpdateTime(System.currentTimeMillis());
            inquiryRepository.save(inquiry);
            InquiryExternalRecord externalInquiryListLogInquiryListLog = new InquiryExternalRecord();
            externalInquiryListLogInquiryListLog.setCreateRoleId(sysUser.getUserId());
            externalInquiryListLogInquiryListLog.setRoleId(sysUser.getMemberRoleId());
            externalInquiryListLogInquiryListLog.setCreateTime(System.currentTimeMillis());
            externalInquiryListLogInquiryListLog.setState(taskResultVOWrapper.getData().getStatus());
            externalInquiryListLogInquiryListLog.setRoleName(sysUser.getMemberRoleName());
            externalInquiryListLogInquiryListLog.setOperationTime(System.currentTimeMillis());
            externalInquiryListLogInquiryListLog.setOperation(operation);
            externalInquiryListLogInquiryListLog.setRoleName(sysUser.getMemberRoleName());
            externalInquiryListLogInquiryListLog.setInquiryListId(inquiry.getId());
            externalInquiryListLogInquiryListLog.setAuditOpinion(cause);
            inquiryExternalRecordRepository.save(externalInquiryListLogInquiryListLog);
        }
        return taskResultVOWrapper;
    }


    /**
     * 工作流内部批量审核
     * @param: cause 审核原因, state 审核状态1.通过 0.不通过 -1, inquiry：商品询价单
     * @return 执行工作流结果
     * @author wrc
     * 2020/8/11 17:23
     */
    private Wrapper auditInteriorAll(List<Inquiry> inquirys, Integer state, UserLoginCacheDTO sysUser, String operation) {
        //添加需求报价单内部流转记录
        for (Inquiry inquiry : inquirys) {
            TaskExecuteVO processStartVO = new TaskExecuteVO();
            processStartVO.setRoleId(sysUser.getMemberRoleId());
            processStartVO.setAgree(state);
            processStartVO.setTaskId(inquiry.getInteriorTaskId());
            processStartVO.setMemberId(sysUser.getMemberId());
            processStartVO.setProcessKey(ProcessEnum.TRADE_INQUIRY_INNER.getProcessKey());
            processStartVO.setDataId(inquiry.getId());
            Wrapper<SimpleTaskCompleteVO> taskResultVOWrapper = processFeign.completeSimpleTask(processStartVO);
            if (ResponseCode.SUCCESS.getCode() == taskResultVOWrapper.getCode()) {
                inquiry.setInteriorTaskId(taskResultVOWrapper.getData().getTaskId());
                inquiry.setInteriorState(taskResultVOWrapper.getData().getStatus());
                inquiry.setUpdateTime(System.currentTimeMillis());
                inquiryRepository.save(inquiry);
                InquiryInteriorRecord interiorInquiryListLog = new InquiryInteriorRecord();
                interiorInquiryListLog.setCreateRoleId(sysUser.getUserId());
                interiorInquiryListLog.setRoleId(sysUser.getMemberRoleId());
                interiorInquiryListLog.setCreateTime(System.currentTimeMillis());
                interiorInquiryListLog.setDepartment(sysUser.getUserOrgName());
                interiorInquiryListLog.setState(taskResultVOWrapper.getData().getStatus());
                interiorInquiryListLog.setRoleName(sysUser.getUserName());
                interiorInquiryListLog.setPosition(sysUser.getUserJobTitle());
                interiorInquiryListLog.setOperationTime(System.currentTimeMillis());
                interiorInquiryListLog.setOperation(operation);
                interiorInquiryListLog.setInquiryListId(inquiry.getId());
                interiorInquiryListLog.setAuditOpinion("");
                inquiryInteriorRecordRepository.save(interiorInquiryListLog);
            } else {
                return taskResultVOWrapper;
            }
        }
        return Wrapper.success();
    }


//    /**
//     * sql拼接
//     * @author wrc
//     * @date 2020/7/31
//     */
//    private String sqlJointList(InquiryListRequest request, String condition) {
//        StringBuilder sbList = new StringBuilder();
//        sbList.append("SELECT rf.is_quoted as isQuoted,rf.create_time as voucherTime,rf.create_time as createTime,rf.member_name as memberName,rf.member_id as memberId,rf.create_member_name as inquiryListMemberName,rf.create_member_id as inquiryListMemberId,rf.inquiry_list_no as inquiryListNo,rf.id as id,rf.details as details,rf.delivery_time as deliveryTime,rf.quotation_as_time as quotationAsTime,rf.external_state as externalState,rf.interior_state as interiorState, rf.is_second_inquiry as isShowSecondInquiry, " +
//                " (select tip.img_url from trade_inquiry_product tip where tip.inquiry_list_id = rf.id limit 1) as imgUrl " +
//                "FROM trade_inquiry rf  ");
//        sbList.append(condition);
//        sbList.append(" order by  rf.create_time desc ");
//        sbList.append(" limit ");
//        sbList.append(request.getPageSize());
//        sbList.append(" OFFSET ");
//        sbList.append(request.getCurrent() * request.getPageSize());
//        return sbList.toString();
//    }
//
//    /**
//     * sql拼接
//     * @author wrc
//     * @date 2020/7/31
//     */
//    private String sqlJointCount(String condition) {
//        String sbCount = "SELECT count(DISTINCT rf.id) FROM trade_inquiry rf " +
//                condition;
//        return sbCount;
//    }
//
//    /**
//     * sql拼接
//     * @P queryType 查询类型：1.报价单查询 2. 待新增报价单查询 3.待审核报价单（一级） 4.待审核报价单（二级） 5.待提交报价单
//     * @author wrc
//     * @date 2020/7/31
//     */
//    private String sqlJointConditionProduct(InquiryListRequest request, Long memberId, Long memberRolId, Integer queryType) {
//        StringBuilder sbCondition = new StringBuilder();
//        sbCondition.append(" where  rf.member_id =");
//        sbCondition.append(memberId);
//        sbCondition.append(" and rf.member_role_id =");
//        sbCondition.append(memberRolId);
//        if (null != request && null != request.getDetails() && !request.getDetails().isEmpty()) {
//            sbCondition.append(" AND  rf.details like  '%");
//            sbCondition.append(request.getDetails());
//            sbCondition.append("%'");
//        }
//        if (null != request && null != request.getInquiryListNo() && !request.getInquiryListNo().isEmpty()) {
//            sbCondition.append(" AND  rf.inquiry_list_no like  '%");
//            sbCondition.append(request.getInquiryListNo());
//            sbCondition.append("%'");
//        }
//
//        if (null != request && null != request.getMemberName() && !request.getMemberName().isEmpty()) {
//            sbCondition.append(" AND  rf.member_name like  '%");
//            sbCondition.append(request.getMemberName());
//            sbCondition.append("%'");
//        }
//
//        if (null != request && null != request.getInquiryListMemberName() && !request.getInquiryListMemberName().isEmpty()) {
//            sbCondition.append(" AND  rf.create_member_name like  '%");
//            sbCondition.append(request.getMemberName());
//            sbCondition.append("%'");
//        }
//        if (null != request && null != request.getStartDocumentsTime() && null != request.getEndDocumentsTime()) {
//            sbCondition.append(" AND  rf.voucher_time BETWEEN ");
//            sbCondition.append(request.getStartDocumentsTime());
//            sbCondition.append(" and ");
//            sbCondition.append(request.getEndDocumentsTime());
//        }
//        if (queryType.equals(OrderConstant.InquiryQueryType.INQUIRY_ALL)) {
//            if (request != null && null != request.getExternalState()) {
//                sbCondition.append(" AND  rf.external_state = ");
//                sbCondition.append(request.getExternalState());
//            }
//            if (request != null && null != request.getInteriorState()) {
//                sbCondition.append(" AND  rf.interior_state = ");
//                sbCondition.append(request.getInteriorState());
//            }
//        } else if (queryType.equals(OrderConstant.InquiryQueryType.INQUIRY_NOT_SUBMIT)) {
//            sbCondition.append(" and  (rf.interior_state in(1,6,7)");
//            if (request != null && null != request.getInteriorState()) {
//                sbCondition.append(" AND  rf.interior_state = ");
//                sbCondition.append(request.getInteriorState());
//            }
//        } else if (queryType.equals(OrderConstant.InquiryQueryType.INQUIRY_CHECK_ONE)) {
//            sbCondition.append(" and rf.interior_state =2");
//        } else if (queryType.equals(OrderConstant.InquiryQueryType.INQUIRY_CHECK_TWO)) {
//            sbCondition.append(" and rf.interior_state =3");
//        } else if (queryType.equals(OrderConstant.InquiryQueryType.INQUIRY_NOT_CONFIRM)) {
//            sbCondition.append(" and rf.interior_state =4");
//        }else if (queryType.equals(OrderConstant.InquiryQueryType.PRODUCT_QUOTATION_TO_BE_SUBMITTED)) {
//            sbCondition.append(" and rf.external_state in(1,2,3,4,5)");
//            if (request != null && null != request.getExternalState()) {
//                sbCondition.append(" and rf.external_state = ");
//                sbCondition.append(request.getExternalState());
//            } else {
//                sbCondition.append(" and rf.external_state in(2,3,4,5)");
//
//            }
//        }
//        return sbCondition.toString();
//    }
//
//    /**
//     * sql拼接
//     * queryType 查询类型：1.报价单查询 2. 待新增报价单查询 3.待审核报价单（一级） 4.待审核报价单（二级） 5.待提交报价单
//     * @author wrc
//     * @date 2020/7/31
//     */
//    private String sqlJointCondition(InquiryListRequest request, Long memberId, Long createRoleId, Integer queryType) {
//        StringBuilder sbCondition = new StringBuilder();
//        sbCondition.append(" where 1=1 ");
//        sbCondition.append(" AND  rf.create_member_id =");
//        sbCondition.append(memberId);
//        sbCondition.append(" AND  rf.create_role_id =");
//        sbCondition.append(createRoleId);
//        if (null != request && null != request.getKeyword() && !request.getKeyword().isEmpty()) {
//            sbCondition.append(" AND  (rf.details like  '%");
//            sbCondition.append(request.getKeyword());
//            sbCondition.append("%'");
//            sbCondition.append(" or  rf.inquiry_list_no like  '%");
//            sbCondition.append(request.getKeyword());
//            sbCondition.append("%')");
//        }
//        if (null != request && null != request.getDetails() && !request.getDetails().isEmpty()) {
//            sbCondition.append(" AND  rf.details like  '%");
//            sbCondition.append(request.getDetails());
//            sbCondition.append("%'");
//        }
//        if (null != request && null != request.getInquiryListNo() && !request.getInquiryListNo().isEmpty()) {
//            sbCondition.append(" AND  rf.inquiry_list_no like  '%");
//            sbCondition.append(request.getInquiryListNo());
//            sbCondition.append("%'");
//        }
//        if (null != request && null != request.getInquiryListMemberName() && !request.getInquiryListMemberName().isEmpty()) {
//            sbCondition.append(" AND  rf.create_member_name like  '%");
//            sbCondition.append(request.getInquiryListMemberName());
//            sbCondition.append("%'");
//        }
//        if (null != request && null != request.getMemberName() && !request.getMemberName().isEmpty()) {
//            sbCondition.append(" AND  rf.member_name like  '%");
//            sbCondition.append(request.getMemberName());
//            sbCondition.append("%'");
//        }
//        if (null != request && null != request.getStartDocumentsTime() && null != request.getEndDocumentsTime()) {
//            sbCondition.append(" AND  rf.voucher_time BETWEEN ");
//            sbCondition.append(request.getStartDocumentsTime());
//            sbCondition.append(" and ");
//            sbCondition.append(request.getEndDocumentsTime());
//        }
//        if (queryType.equals(OrderConstant.InquiryQueryType.INQUIRY_ALL)) {
//            if (request != null && request.getExternalState() != null) {
//                sbCondition.append(" AND  rf.external_state = ");
//                sbCondition.append(request.getExternalState());
//            }
//            if (request != null && request.getInteriorState() != null) {
//                sbCondition.append(" AND  rf.interior_state = ");
//                sbCondition.append(request.getInteriorState());
//            }
//        } else if (queryType.equals(OrderConstant.InquiryQueryType.INQUIRY_NOT_SUBMIT)) {
//            if (request != null && request.getInteriorState() != null) {
//                sbCondition.append(" AND  rf.interior_state = ");
//                sbCondition.append(request.getInteriorState());
//            } else {
//                sbCondition.append(" and  rf.interior_state in(1,6,7) ");
//            }
//        } else if (queryType.equals(OrderConstant.InquiryQueryType.INQUIRY_CHECK_ONE)) {
//            sbCondition.append(" and rf.interior_state =2");
//        } else if (queryType.equals(OrderConstant.InquiryQueryType.INQUIRY_CHECK_TWO)) {
//            sbCondition.append(" and rf.interior_state =3");
//        } else if (queryType.equals(OrderConstant.InquiryQueryType.INQUIRY_NOT_CONFIRM)) {
//            sbCondition.append(" and rf.interior_state =4");
//        } else if (queryType.equals(OrderConstant.InquiryQueryType.PRODUCT_QUOTATION_TO_BE_SUBMITTED)) {
//            sbCondition.append(" and rf.external_state in(2,3,4,5)");
//        }
//        return sbCondition.toString();
//    }


    /**
     * 增加减记录操作数据记录
     * @author wrc
     * @date 2020/11/26
     */
    @Async
    public void countList(String increaseTitle, Long memberId, Long memberRoleId, Integer dataSource, Long IncreaseCount, Integer increaseOperateType, Long reduceCount, Integer reduceOperateType) {
        try {
            OperateNoticeVO operateNoticeVO = new OperateNoticeVO();
            operateNoticeVO.setIncreaseTitle(increaseTitle);
            operateNoticeVO.setDataSource(dataSource);
            operateNoticeVO.setMemberId(memberId);
            operateNoticeVO.setRoleId(memberRoleId);
            operateNoticeVO.setReduceCount(reduceCount);
            operateNoticeVO.setReduceOperateType(reduceOperateType);
            operateNoticeVO.setIncreaseCount(IncreaseCount);
            operateNoticeVO.setIncreaseOperateType(increaseOperateType);
            reportControllerFeign.addOperateNotice(operateNoticeVO);
        } catch (Exception e) {
            log.error("订单数据统计异常", e);
        }
    }

    /**
     * 发消息
     */
    @Async
    public void sendSystemMessage(Inquiry inquiry, String name) {
        try {
            SystemMessageRequest systemMessageRequest = new SystemMessageRequest();
            systemMessageRequest.setMemberId(inquiry.getCreateMemberId());
            systemMessageRequest.setRoleId(inquiry.getCreateRoleId());
            systemMessageRequest.setMessageNotice(name);
            systemMessageRequest.setParams(Arrays.asList(inquiry.getInquiryListNo(), inquiry.getDetails()));
            systemMessageControllerFeign.sendSystemMessage(systemMessageRequest);
        } catch (Exception e) {
            log.error("发送订单通知消息异常", e);
        }
    }

    /**
     * 发消息
     */
    @Async
    public void batchSendSystemMessage(List<Inquiry> inquirys, String name) {
        try {
            List<SystemMessageRequest> collect = inquirys.stream().map(temp -> {
                SystemMessageRequest systemMessageRequest = new SystemMessageRequest();
                systemMessageRequest.setMemberId(temp.getCreateMemberId());
                systemMessageRequest.setRoleId(temp.getCreateRoleId());
                systemMessageRequest.setMessageNotice(name);
                systemMessageRequest.setParams(Arrays.asList(temp.getInquiryListNo(), temp.getDetails()));
                return systemMessageRequest;
            }).collect(Collectors.toList());
            systemMessageControllerFeign.batchSendSystemMessage(collect);
        } catch (Exception e) {
            log.error("发送订单通知消息异常", e);
        }
    }

    /**
     * 构建查询条件
     */
    private Specification<Inquiry> getSpecification(InquiryListRequest request, Long createMemberId, Long createMemberRoleId, Long memberId, Long memberRoleId, Integer queryType) {
        return (Specification<Inquiry>) (root, query, criteriaBuilder) -> {
            Predicate finalConditions = criteriaBuilder.conjunction();

            String keyword = request.getKeyword();
            String details = request.getDetails();
            String inquiryListNo = request.getInquiryListNo();
            String inquiryListMemberName = request.getInquiryListMemberName();
            String memberName = request.getMemberName();
            Long startDocumentsTime = request.getStartDocumentsTime();
            Long endDocumentsTime = request.getEndDocumentsTime();
            Integer externalState = request.getExternalState();
            Integer interiorState = request.getInteriorState();

            //询价会员id
            if (createMemberId != null && createMemberId > 0) {
                finalConditions = criteriaBuilder.and(finalConditions, criteriaBuilder.equal(root.get("createMemberId"), createMemberId));
            }
            //询价会员角色id
            if (createMemberRoleId != null && createMemberRoleId > 0) {
                finalConditions = criteriaBuilder.and(finalConditions, criteriaBuilder.equal(root.get("createRoleId"), createMemberRoleId));
            }
            //报价会员id
            if (memberId != null && memberId > 0) {
                finalConditions = criteriaBuilder.and(finalConditions, criteriaBuilder.equal(root.get("memberId"), memberId));
            }
            //报价会员角色id
            if (memberRoleId != null && memberRoleId > 0) {
                finalConditions = criteriaBuilder.and(finalConditions, criteriaBuilder.equal(root.get("memberRoleId"), memberRoleId));
            }
            //关键字
            if(StringUtils.isNotEmpty(keyword)){
                Predicate predicate = criteriaBuilder.or(criteriaBuilder.like(root.get("details"), "%" + keyword + "%"), criteriaBuilder.like(root.get("inquiryListNo"), "%" + keyword + "%"));
                finalConditions = criteriaBuilder.and(finalConditions, predicate);
            }
            //描述
            if(StringUtils.isNotEmpty(details)){
                Predicate predicate = criteriaBuilder.like(root.get("details"), "%" + details + "%");
                finalConditions = criteriaBuilder.and(finalConditions, predicate);
            }
            //询价单号
            if(StringUtils.isNotEmpty(inquiryListNo)){
                Predicate predicate = criteriaBuilder.like(root.get("inquiryListNo"), "%" + inquiryListNo + "%");
                finalConditions = criteriaBuilder.and(finalConditions, predicate);
            }
            //询价会员名称
            if(StringUtils.isNotEmpty(inquiryListMemberName)){
                Predicate predicate = criteriaBuilder.like(root.get("createMemberName"), "%" + inquiryListMemberName + "%");
                finalConditions = criteriaBuilder.and(finalConditions, predicate);
            }
            //报价会员名称
            if(StringUtils.isNotEmpty(memberName)){
                Predicate predicate = criteriaBuilder.like(root.get("memberName"), "%" + memberName + "%");
                finalConditions = criteriaBuilder.and(finalConditions, predicate);
            }
            //开始单据时间
            if(startDocumentsTime != null && startDocumentsTime > 0){
                finalConditions = criteriaBuilder.and(finalConditions, criteriaBuilder.ge(root.get("voucherTime"), startDocumentsTime));
            }
            //结束单据时间
            if(endDocumentsTime != null && endDocumentsTime > 0){
                finalConditions = criteriaBuilder.and(finalConditions, criteriaBuilder.le(root.get("voucherTime"), endDocumentsTime));
            }
            //状态
            if (queryType.equals(OrderConstant.InquiryQueryType.INQUIRY_ALL)) {
                if (externalState != null && externalState > 0) {
                    finalConditions = criteriaBuilder.and(finalConditions, criteriaBuilder.equal(root.get("externalState"), externalState));
                }
                if (interiorState != null && interiorState > 0) {
                    finalConditions = criteriaBuilder.and(finalConditions, criteriaBuilder.equal(root.get("interiorState"), interiorState));
                }
            } else if (queryType.equals(OrderConstant.InquiryQueryType.INQUIRY_NOT_SUBMIT)) {
                if (interiorState != null && interiorState > 0) {
                    finalConditions = criteriaBuilder.and(finalConditions, criteriaBuilder.equal(root.get("interiorState"), interiorState));
                } else {
                    List<Integer> stateList = new ArrayList<>();
                    stateList.add(1);
                    stateList.add(6);
                    stateList.add(7);
                    finalConditions = criteriaBuilder.and(finalConditions, criteriaBuilder.in(root.get("interiorState")).value(stateList));
                }
            } else if (queryType.equals(OrderConstant.InquiryQueryType.INQUIRY_CHECK_ONE)) {
                finalConditions = criteriaBuilder.and(finalConditions, criteriaBuilder.equal(root.get("interiorState"), 2));
            } else if (queryType.equals(OrderConstant.InquiryQueryType.INQUIRY_CHECK_TWO)) {
                finalConditions = criteriaBuilder.and(finalConditions, criteriaBuilder.equal(root.get("interiorState"), 3));
            } else if (queryType.equals(OrderConstant.InquiryQueryType.INQUIRY_NOT_CONFIRM)) {
                finalConditions = criteriaBuilder.and(finalConditions, criteriaBuilder.equal(root.get("interiorState"), 4));
            } else if (queryType.equals(OrderConstant.InquiryQueryType.PRODUCT_QUOTATION_TO_BE_SUBMITTED)) {
                if(externalState != null && externalState > 0){
                    finalConditions = criteriaBuilder.and(finalConditions, criteriaBuilder.equal(root.get("externalState"), externalState));
                }else{
                    List<Integer> stateList = new ArrayList<>();
                    stateList.add(2);
                    stateList.add(3);
                    stateList.add(4);
                    stateList.add(5);
                    finalConditions = criteriaBuilder.and(finalConditions, criteriaBuilder.in(root.get("externalState")).value(stateList));
                }
            }

            //排序
            Order createTimeOrder = criteriaBuilder.desc(root.get("createTime"));

            return query.orderBy(createTimeOrder).where(finalConditions).getRestriction();
        };
    }

    /**
     * 构建查询条件
     */
    private Specification<Inquiry> getNotAssignedInquirySpecification(NotAssignedInquiryRequest request, Long memberId, Long memberRoleId) {
        return (Specification<Inquiry>) (root, query, criteriaBuilder) -> {
            Predicate finalConditions = criteriaBuilder.conjunction();

            String details = request.getDetails();
            String inquiryListNo = request.getInquiryListNo();
            String memberName = request.getMemberName();
            Long startDocumentsTime = request.getStartDocumentsTime();
            Long endDocumentsTime = request.getEndDocumentsTime();
            Integer externalState = request.getExternalState();
            Integer interiorState = request.getInteriorState();

            //用户id(待领取查用户id为null的数据)
            finalConditions = criteriaBuilder.and(finalConditions, criteriaBuilder.isNull(root.get("quoteUserId")));

            //描述
            if(StringUtils.isNotEmpty(details)){
                Predicate predicate = criteriaBuilder.like(root.get("details"), "%" + details + "%");
                finalConditions = criteriaBuilder.and(finalConditions, predicate);
            }
            //询价单号
            if(StringUtils.isNotEmpty(inquiryListNo)){
                Predicate predicate = criteriaBuilder.like(root.get("inquiryListNo"), "%" + inquiryListNo + "%");
                finalConditions = criteriaBuilder.and(finalConditions, predicate);
            }
            //报价会员名称
            if(StringUtils.isNotEmpty(memberName)){
                Predicate predicate = criteriaBuilder.like(root.get("memberName"), "%" + memberName + "%");
                finalConditions = criteriaBuilder.and(finalConditions, predicate);
            }
            //开始单据时间
            if(startDocumentsTime != null && startDocumentsTime > 0){
                finalConditions = criteriaBuilder.and(finalConditions, criteriaBuilder.ge(root.get("voucherTime"), startDocumentsTime));
            }
            //结束单据时间
            if(endDocumentsTime != null && endDocumentsTime > 0){
                finalConditions = criteriaBuilder.and(finalConditions, criteriaBuilder.le(root.get("voucherTime"), endDocumentsTime));
            }
            //状态
            if (externalState != null && externalState > 0) {
                finalConditions = criteriaBuilder.and(finalConditions, criteriaBuilder.equal(root.get("externalState"), externalState));
            }
            if (interiorState != null && interiorState > 0) {
                finalConditions = criteriaBuilder.and(finalConditions, criteriaBuilder.equal(root.get("interiorState"), interiorState));
            }
            //会员
            if (memberId != null && memberId > 0) {
                finalConditions = criteriaBuilder.and(finalConditions, criteriaBuilder.equal(root.get("memberId"), memberId));
            }
            if (memberRoleId != null && memberRoleId > 0) {
                finalConditions = criteriaBuilder.and(finalConditions, criteriaBuilder.equal(root.get("memberRoleId"), memberRoleId));
            }

            //排序
            Order createTimeOrder = criteriaBuilder.desc(root.get("createTime"));

            return query.orderBy(createTimeOrder).where(finalConditions).getRestriction();
        };
    }

    /**
     * 获取询价单内部操作流程
     */
    private void getInqyiryLog(InquiryListDetailsResponse response, Long id, UserLoginCacheDTO sysUser) {
        List<InquiryInteriorRecord> interiorLogs = inquiryInteriorRecordRepository.findAllByInquiryListIdEquals(id);
        //查询内部流转
        InternalProcessQueryVO taskParamQueryVO = new InternalProcessQueryVO();
        taskParamQueryVO.setProcessKey(ProcessEnum.TRADE_INQUIRY_INNER.getProcessKey());
        Wrapper<SimpleProcessDefVO> listWrapper = processFeign.findSimpleInternalTaskDefinitions(taskParamQueryVO);
        List<LogStateResponse> interiorList = new ArrayList<>();
        if (ResponseCode.SUCCESS.getCode() != listWrapper.getCode()) {
            throw new RuntimeException(listWrapper.getMessage());
        }
        List<SimpleTaskVO> data = listWrapper.getData().getTasks();
        data.forEach(taskStepQueryVO -> {
            LogStateResponse workflowLog = new LogStateResponse();
            workflowLog.setState(taskStepQueryVO.getTaskStep());
            workflowLog.setStateName(InquiryInteriorStatusEnum.getName(taskStepQueryVO.getTaskStep()));
            workflowLog.setOperationalProcess(taskStepQueryVO.getTaskName());
            workflowLog.setRoleName(taskStepQueryVO.getRoleName());
            if (CollectionUtils.isEmpty(interiorLogs)) {
                workflowLog.setIsExecute(OrderConstant.State.STOP);
            } else {
                //获取最后一个执行的步骤
                workflowLog.setIsExecute(interiorLogs.get(interiorLogs.size() - 1).getState() - 1 >= taskStepQueryVO.getTaskStep() ? OrderConstant.State.START : OrderConstant.State.STOP);
            }
            interiorList.add(workflowLog);
        });
        if (!CollectionUtils.isEmpty(interiorList)) {
            interiorList.get(0).setIsExecute(OrderConstant.State.START);
        }
        response.setInteriorRequisitionFormStateResponses(interiorList);
        if (CollectionUtils.isEmpty(interiorLogs)) {
            return;
        }
        List<InteriorInquiryListLogResponse> interiorLogsResponse = interiorLogs.stream().map(interiorInquiryListLog -> {
            InteriorInquiryListLogResponse interiorInquiryListLogResponse = new InteriorInquiryListLogResponse();
            BeanUtils.copyProperties(interiorInquiryListLog, interiorInquiryListLogResponse);
            interiorInquiryListLogResponse.setStateName(InquiryInteriorStatusEnum.getName(interiorInquiryListLogResponse.getState()));
            return interiorInquiryListLogResponse;
        }).collect(Collectors.toList());
        response.setInteriorInquiryListLogResponses(interiorLogsResponse.stream().sorted(Comparator.comparing(InteriorInquiryListLogResponse::getOperationTime)).collect(Collectors.toList()));
    }

    /**
     * 获取询价单外部操作流程
     */
    private void getExternalLog(InquiryListDetailsResponse response, Long id, UserLoginCacheDTO sysUser) {
        List<InquiryExternalRecord> externalRequisitionForms = inquiryExternalRecordRepository.findAllByInquiryListIdEquals(id);
        //查询外部流转
        ExternalProcessQueryVO taskStepVO = new ExternalProcessQueryVO();
        taskStepVO.setProcessKey(ProcessEnum.TRADE_INQUIRY_EXTERNAL.getProcessKey());
        Wrapper<SimpleProcessDefVO> wrapper = processFeign.findSimpleExternalTaskDefinitions(taskStepVO);
        List<LogStateResponse> externalList = new ArrayList<>();
        if (ResponseCode.SUCCESS.getCode() != wrapper.getCode()) {
            throw new RuntimeException(wrapper.getMessage());
        }
        List<SimpleTaskVO> data = wrapper.getData().getTasks();
        data.forEach(taskStepQueryVO -> {
            LogStateResponse quotationState = new LogStateResponse();
            if (!CollectionUtils.isEmpty(externalRequisitionForms)) {
                Integer state = externalRequisitionForms.get(externalRequisitionForms.size() - 1).getState();
                quotationState.setIsExecute(state >= taskStepQueryVO.getTaskStep() ? OrderConstant.State.START : OrderConstant.State.STOP);
            } else {
                quotationState.setIsExecute(OrderConstant.State.STOP);
            }
            quotationState.setOperationalProcess(taskStepQueryVO.getTaskName());
            quotationState.setRoleName(taskStepQueryVO.getRoleName());
            quotationState.setState(taskStepQueryVO.getTaskStep());

            externalList.add(quotationState);
        });
        if (!CollectionUtils.isEmpty(externalList)) {
            externalList.get(0).setIsExecute(OrderConstant.State.START);
        }
        response.setExternalInquiryListStateResponses(externalList);
        if (CollectionUtils.isEmpty(externalRequisitionForms)) {
            return;
        }
        //查询外部和内部工作流记录
        List<ExternalInquiryListLogResponse> externalInquiryListLogResponseList = externalRequisitionForms.stream().map(externalInquiryListLog -> {
            ExternalInquiryListLogResponse externalInquiryListLogResponse = new ExternalInquiryListLogResponse();
            BeanUtils.copyProperties(externalInquiryListLog, externalInquiryListLogResponse);
            externalInquiryListLogResponse.setStateName(InquiryExternalStatusEnum.getName(externalInquiryListLogResponse.getState()));
            return externalInquiryListLogResponse;
        }).collect(Collectors.toList());
        response.setExternalInquiryListLogResponses(externalInquiryListLogResponseList);

    }

    /**
     * 商品询价--内部流转记录--操作日志
     * @param inquiryListId 商品询价单ID
     * @param startTime 开始时间
     * @param endTime 结束时间
     */
    @Override
    public Page<InquiryInteriorRecord> getInquiryInteriorRecordList(PageVO pageVO, Long inquiryListId, Long startTime, Long endTime) {
        Pageable page = PageRequest.of(pageVO.getCurrent() - 1, pageVO.getPageSize());
        return inquiryInteriorRecordRepository.findAll(getInquiryInteriorRecordSpecification(inquiryListId, startTime, endTime), page);
    }

    /**
     * 构建查询条件
     */
    private Specification<InquiryInteriorRecord> getInquiryInteriorRecordSpecification(Long inquiryListId, Long startTime, Long endTime){
        return (Specification<InquiryInteriorRecord>) (root, query, criteriaBuilder) -> {
            Predicate finalConditions = criteriaBuilder.conjunction();

            if(inquiryListId != null && inquiryListId > 0){
                finalConditions = criteriaBuilder.and(finalConditions, criteriaBuilder.equal(root.get("inquiryListId"), inquiryListId));
            }

            if(startTime != null && startTime > 0){
                finalConditions = criteriaBuilder.and(finalConditions, criteriaBuilder.ge(root.get("createTime"), startTime));
            }

            if(endTime != null && endTime > 0){
                finalConditions = criteriaBuilder.and(finalConditions, criteriaBuilder.le(root.get("createTime"), endTime));
            }

            //排序
            Order idOrder = criteriaBuilder.desc(root.get("id"));

            return  query.orderBy(idOrder).where(finalConditions).getRestriction();
        };
    }

    /**
     * 商品询价--外部流转记录--操作日志
     * @param inquiryListId 商品询价单ID
     * @param startTime 开始时间
     * @param endTime 结束时间
     */
    @Override
    public Page<InquiryExternalRecord> getInquiryExternalRecordList(PageVO pageVO, Long inquiryListId, Long startTime, Long endTime) {
        Pageable page = PageRequest.of(pageVO.getCurrent() - 1, pageVO.getPageSize());
        return inquiryExternalRecordRepository.findAll(getInquiryExternalRecordSpecification(inquiryListId, startTime, endTime), page);
    }

    /**
     * 询价报价-待分配询价单查询-领取
     */
    @Override
    public Boolean assignedInquiry(Long inquiryId, UserLoginCacheDTO sysUser) {
        Inquiry inquiry = inquiryRepository.findById(inquiryId).orElse(null);
        if(inquiry != null){
            inquiry.setQuoteUserId(sysUser.getUserId());
            inquiry.setQuoteUserName(sysUser.getUserName());
            inquiryRepository.saveAndFlush(inquiry);
            return true;
        }else{
            throw new BusinessException(ResponseCode.TRANSACTION_INQUIRY_NOT_EXIST);
        }
    }

    /**
     * 询价报价-待分配询价单查询-批量领取
     */
    @Override
    public Boolean assignedInquiryBatch(List<Long> idList, UserLoginCacheDTO sysUser) {
        List<Inquiry> inquiryList = inquiryRepository.findAllById(idList);
        if(inquiryList.size() == idList.size()){
            inquiryList.forEach(inquiry -> {
                inquiry.setQuoteUserId(sysUser.getUserId());
                inquiry.setQuoteUserName(sysUser.getUserName());
            });
            inquiryRepository.saveAll(inquiryList);
            return true;
        }else{
            throw new BusinessException(ResponseCode.TRANSACTION_INQUIRY_NOT_EXIST);
        }
    }

    /**
     * 构建查询条件
     */
    private Specification<InquiryExternalRecord> getInquiryExternalRecordSpecification(Long inquiryListId, Long startTime, Long endTime){
        return (Specification<InquiryExternalRecord>) (root, query, criteriaBuilder) -> {
            Predicate finalConditions = criteriaBuilder.conjunction();

            if(inquiryListId != null && inquiryListId > 0){
                finalConditions = criteriaBuilder.and(finalConditions, criteriaBuilder.equal(root.get("inquiryListId"), inquiryListId));
            }

            if(startTime != null && startTime > 0){
                finalConditions = criteriaBuilder.and(finalConditions, criteriaBuilder.ge(root.get("createTime"), startTime));
            }

            if(endTime != null && endTime > 0){
                finalConditions = criteriaBuilder.and(finalConditions, criteriaBuilder.le(root.get("createTime"), endTime));
            }

            //排序
            Order idOrder = criteriaBuilder.desc(root.get("id"));

            return  query.orderBy(idOrder).where(finalConditions).getRestriction();
        };
    }

    /**
     * 小程序-业务员 询价报价 询价单查询
     *
     * @param request
     * @param sysUser
     * @return
     */
    @Override
    public Wrapper<PageData<AppletQuoteListResponse>> appletInquiryList(AppletInquiryListRequest request, UserLoginCacheDTO sysUser) {
        Pageable page = PageRequest.of(request.getCurrent(), request.getPageSize());
        Page<Inquiry> result = inquiryRepository.findAll(getSpecification(request, sysUser),page);
        Map<Long, String> memberLogoMap = getInquiryCreateMemberInfo(result);
        List<AppletQuoteListResponse> inquiryListResponseList = getAppletInquiryResponse(result,memberLogoMap);
        return Wrapper.success(new PageData<>(result.getTotalElements(), inquiryListResponseList));
    }

    /**
     * 获取询价会员logo
     * @param result
     * @return
     */
    private Map<Long, String> getInquiryCreateMemberInfo(Page<Inquiry> result) {
        Map<Long, String> memberLogoMap = Maps.newHashMap();
        List<Long> memberIdList = result
                .getContent()
                .stream()
                .map(Inquiry::getCreateMemberId)
                .collect(Collectors.toList());
        Wrapper<List<MemberFeignLogoVO>> wrapper = memberInnerControllerFeign.getMemberLogos(memberIdList);
        if (wrapper.getCode() == ResponseCode.SUCCESS.getCode()) {
            memberLogoMap = wrapper
                    .getData()
                    .stream()
                    .collect(Collectors.toMap(MemberFeignLogoVO::getMemberId, MemberFeignLogoVO::getLogo));
        }
        return memberLogoMap;
    }

    /**
     * 构建业务员询价报价单查询条件
     * 不查外部状态为待提交询价单的询价单
     * @param request
     * @param sysUser
     * @return
     */
    private Specification<Inquiry> getSpecification(AppletInquiryListRequest request, UserLoginCacheDTO sysUser) {
        //询价单摘要，询价会员
        String keyword = request.getKeyword();
        //排序类型
        int sortType = request.getSortType();
        //要查询的外部状态
        List<Integer> externalStatusList = InquiryExternalStatusEnum.getStateList()
                .stream()
                .filter(item -> !InquiryExternalStatusEnum.INQUIRY_SHEET_TO_BE_SUBMITTED.getState().equals(item))
                .collect(Collectors.toList());

        return (root, query, criteriaBuilder) -> {
            Predicate finalConditions = criteriaBuilder.conjunction();

            //关键字
            if (StringUtils.isNotEmpty(keyword)) {
                Predicate predicate = criteriaBuilder.or(criteriaBuilder.like(root.get("details"), "%" + keyword + "%"), criteriaBuilder.like(root.get("createMemberName"), "%" + keyword + "%"));
                finalConditions = criteriaBuilder.and(finalConditions, predicate);
            }

            //外部状态
            if (CollectionUtil.isNotEmpty(externalStatusList)) {
                finalConditions = criteriaBuilder.and(finalConditions, criteriaBuilder.in(root.get("externalState")).value(externalStatusList));
            }

            //查询属于自己的询价单
            finalConditions = criteriaBuilder.and(finalConditions, criteriaBuilder.equal(root.get("quoteUserId"),sysUser.getUserId()));

            Order order;
            //不需要联合排序，交付时间和报价截止时间排序单选其一,默认按照单据时间倒序排序
            switch (sortType) {
                case InquirySortTypeConstants.DELIVERY_TIME_ASC_SORT:
                    order = criteriaBuilder.asc(root.get("deliveryTime"));
                    break;
                case InquirySortTypeConstants.DELIVERY_TIME_DESC_SORT:
                    order = criteriaBuilder.desc(root.get("deliveryTime"));
                    break;
                case InquirySortTypeConstants.QUOTATION_AS_TIME_ASC_SORT:
                    order = criteriaBuilder.asc(root.get("quotationAsTime"));
                    break;
                case InquirySortTypeConstants.QUOTATION_AS_TIME_DESC_SORT:
                    order = criteriaBuilder.desc(root.get("quotationAsTime"));
                    break;
                default:
                    order = criteriaBuilder.desc(root.get("createTime"));
            }
            return query.orderBy(order).where(finalConditions).getRestriction();
        };
    }


    /**
     * 获取业务员下级会员的id
     *
     * @param sysUser
     * @return
     */
    @SneakyThrows
    private List<Long> getSubMemberId(UserLoginCacheDTO sysUser) {
        CompletableFuture<List<MemberSalesFindMemberQueryVO>> completableFuture = getSubMemberAsync(sysUser);
        return completableFuture
                .get()
                .stream()
                .map(MemberSalesFindMemberQueryVO::getSubMemberId)
                .collect(Collectors.toList());
    }

    @Async
    protected CompletableFuture<List<MemberSalesFindMemberQueryVO>> getSubMemberAsync(UserLoginCacheDTO sysUser) {
        List<MemberSalesFindMemberQueryVO> subMember = Lists.newArrayList();
        MemberSalesFindMemberVO memberSalesFindMemberVO = new MemberSalesFindMemberVO();
        memberSalesFindMemberVO.setMemberId(sysUser.getMemberId());
        memberSalesFindMemberVO.setUserId(sysUser.getUserId());
        memberSalesFindMemberVO.setMemberRoleId(sysUser.getMemberRoleId());
        Wrapper<List<MemberSalesFindMemberQueryVO>> wrapper = memberAbilitySalesFeign.findMemberSales(memberSalesFindMemberVO);
        if (wrapper.getCode() == ResponseCode.SUCCESS.getCode()) {
            subMember = wrapper.getData();
        }
        return CompletableFuture.completedFuture(subMember);
    }


    /**
     * 获取小程序业务员询价单返回结果
     *
     * @param result
     * @return
     */
    private List<AppletQuoteListResponse> getAppletInquiryResponse(Page<Inquiry> result, Map<Long, String> memberLogoMap) {
        return result
                .getContent()
                .stream()
                .map(inquiry -> {
                    AppletQuoteListResponse appletQuoteListResponse = BeanUtil.copyProperties(inquiry, AppletQuoteListResponse.class);
                    appletQuoteListResponse.setExternalStateName(getExternalStatusName(appletQuoteListResponse.getExternalState()));
                    appletQuoteListResponse.setInteriorStateName(getInteriorStatusName(appletQuoteListResponse.getInteriorState()));
                    appletQuoteListResponse.setInquiryListMemberName(inquiry.getCreateMemberName());
                    appletQuoteListResponse.setInquiryListMemberId(inquiry.getCreateMemberId());
                    appletQuoteListResponse.setIsShowQuote(canShowQuote(appletQuoteListResponse));
                    appletQuoteListResponse.setInquiryMemberLogo(memberLogoMap.get(inquiry.getCreateMemberId()));
                    List<String> mainImgList = inquiry.getInquiryProductList()
                            .stream()
                            .filter(Objects::nonNull)
                            .map(InquiryProduct::getImgUrl)
                            .filter(Objects::nonNull)
                            .collect(Collectors.toList());
                    appletQuoteListResponse.setProductMainImgUrl(CollectionUtil.isNotEmpty(mainImgList) ? mainImgList.get(0) : null);
                    return appletQuoteListResponse;
                })
                .collect(Collectors.toList());
    }

    /**
     * 获取询价报价单内部状态名称
     *
     * @param internalStatus
     * @return
     */
    private String getInteriorStatusName(Integer internalStatus) {
        return InquiryInteriorStatusEnum.getName(internalStatus);
    }

    /**
     * 获取询价报价单外部状态名称
     *
     * @param externalStatus
     * @return
     */
    private String getExternalStatusName(Integer externalStatus) {
        return InquiryExternalStatusEnum.getName(externalStatus);
    }

    /**
     * 是否展示报价按钮
     *
     * @param appletQuoteListResponse
     * @return
     */
    private Boolean canShowQuote(AppletQuoteListResponse appletQuoteListResponse) {
        return InquiryExternalStatusEnum.QUOTATION_TO_BE_SUBMITTED.getState().equals(appletQuoteListResponse.getExternalState());
    }

    /**
     * 小程序业务员询价单详情
     *
     * @param request
     * @param sysUser
     * @return
     */
    @Override
    public Wrapper<AppletInquiryDetailsResponse> appletInquiryDetails(AppletInquiryDetailsRequest request, UserLoginCacheDTO sysUser) {
        Inquiry inquiry = null;
        if (Objects.nonNull(request.getId())) {
            inquiry = getInquiryById(request.getId());
        } else if (StringUtils.isNotEmpty(request.getInquiryNo())) {
            inquiry = getInquiryByNo(request.getInquiryNo());
        }
        if (Objects.isNull(inquiry)) {
            return Wrapper.fail(ResponseCode.RECORDS_DON_T_EXIST);
        }
        AppletInquiryDetailsResponse appletInquiryDetailsResponse = getAppletInquiryDetailResponse(inquiry, sysUser);
        return Wrapper.success(appletInquiryDetailsResponse);
    }

    /**
     * 获取询价单详情
     *
     * @param inquiry
     * @param sysUser
     * @return
     */
    private AppletInquiryDetailsResponse getAppletInquiryDetailResponse(Inquiry inquiry, UserLoginCacheDTO sysUser) {
        AppletInquiryDetailsResponse appletInquiryDetailsResponse = new AppletInquiryDetailsResponse();
        BeanUtils.copyProperties(inquiry, appletInquiryDetailsResponse);
        appletInquiryDetailsResponse.setInquiryListMemberName(inquiry.getCreateMemberName());
        appletInquiryDetailsResponse.setInquiryListMemberId(inquiry.getCreateMemberId());
        appletInquiryDetailsResponse.setExternalStateName(getExternalStateName(inquiry));
        appletInquiryDetailsResponse.setInteriorStateName(getInteriorStateName(inquiry));
        //是否显示报价按钮
        appletInquiryDetailsResponse.setIsShowQuote(canShowQuote(appletInquiryDetailsResponse));
        List<InquiryListProductResponse> products = getInquiryProduct(inquiry.getId());
        appletInquiryDetailsResponse.setInquiryListProductRequests(products);
        //查询外部流转
        getExternalInquiryListLog(appletInquiryDetailsResponse, inquiry.getId(), sysUser);
        //查询内部流转
        getInteriorLog(appletInquiryDetailsResponse, inquiry.getId(), sysUser);
        return appletInquiryDetailsResponse;
    }

    /**
     * 是否展示报价按钮
     *
     * @param appletInquiryDetailsResponse
     * @return
     */
    private Boolean canShowQuote(AppletInquiryDetailsResponse appletInquiryDetailsResponse) {
        return InquiryExternalStatusEnum.QUOTATION_TO_BE_SUBMITTED.getState().equals(appletInquiryDetailsResponse.getExternalState());
    }


    /**
     * 根据询价单id获取询价商品
     *
     * @param id
     * @return
     */
    private List<InquiryListProductResponse> getInquiryProduct(Long id) {
        return inquiryProductRepository.findAllByInquiryIdEquals(id)
                .stream()
                .map(inquiryListProduct -> {
                    InquiryListProductResponse inquiryListResponse = new InquiryListProductResponse();
                    BeanUtils.copyProperties(inquiryListProduct, inquiryListResponse);
                    return inquiryListResponse;
                }).collect(Collectors.toList());
    }

    /**
     * 获取询价单外部状态
     * @param inquiry
     * @return
     */
    private String getExternalStateName(Inquiry inquiry) {
        return InquiryExternalStatusEnum.getName(inquiry.getExternalState());
    }

    /**
     * 获取询价单内部状态
     * @param inquiry
     * @return
     */
    private String getInteriorStateName(Inquiry inquiry) {
        return InquiryInteriorStatusEnum.getName(inquiry.getInteriorState());
    }

    /**
     * 根据询价单id查询询价单
     *
     * @param id
     * @return
     */
    private Inquiry getInquiryById(Long id) {
        return inquiryRepository.findById(id).orElse(null);
    }

    /**
     * 根据询价单号查询询价单
     *
     * @param inquiryNo
     * @return
     */
    private Inquiry getInquiryByNo(String inquiryNo) {
        return inquiryRepository.findByInquiryListNo(inquiryNo);
    }

    /**
     * 询价单外部操作流程记录和状态数据配置
     */
    private void getExternalInquiryListLog(AppletInquiryDetailsResponse response, Long id, UserLoginCacheDTO sysUser) {
        List<InquiryExternalRecord> allByInquiryListIdEquals = inquiryExternalRecordRepository.findAllByInquiryListIdEquals(id);
        //外部单据流转记录
        List<LogStateResponse> externalQuotationStateResponses = new ArrayList<>();
        ExternalProcessQueryVO taskStepVO = new ExternalProcessQueryVO();
        taskStepVO.setProcessKey(ProcessEnum.TRADE_INQUIRY_EXTERNAL.getProcessKey());
        taskStepVO.setRoleId(sysUser.getMemberRoleId());
        Wrapper<SimpleProcessDefVO> listWrapper = processFeign.findSimpleExternalTaskDefinitions(taskStepVO);
        if (ResponseCode.SUCCESS.getCode() != listWrapper.getCode()) {
            return;
        }
        //获取最后一个执行的步骤
        List<SimpleTaskVO> data = listWrapper.getData().getTasks();
        data.forEach(taskStepQueryVO -> {
            LogStateResponse externalRequisitionFormResponse = new LogStateResponse();
            externalRequisitionFormResponse.setState(taskStepQueryVO.getTaskStep());
            externalRequisitionFormResponse.setRoleName(taskStepQueryVO.getRoleName());
            externalRequisitionFormResponse.setOperationalProcess(taskStepQueryVO.getTaskName());
            if (CollectionUtils.isEmpty(allByInquiryListIdEquals)) {
                externalRequisitionFormResponse.setIsExecute(OrderConstant.State.STOP);
            } else {
                //最后一个执行的操作与偶步骤
                Integer state = allByInquiryListIdEquals.get(allByInquiryListIdEquals.size() - 1).getState();
                externalRequisitionFormResponse.setIsExecute(state >= taskStepQueryVO.getTaskStep() ? OrderConstant.State.START : OrderConstant.State.STOP);
            }
            externalQuotationStateResponses.add(externalRequisitionFormResponse);
        });
        if (!CollectionUtils.isEmpty(externalQuotationStateResponses)) {
            externalQuotationStateResponses.get(0).setIsExecute(OrderConstant.State.START);
        }
        response.setExternalInquiryListStateResponses(externalQuotationStateResponses);
        if (CollectionUtils.isEmpty(allByInquiryListIdEquals)) {
            return;
        }
        List<ExternalInquiryListLogResponse> externalInquiryListLogResponses = allByInquiryListIdEquals.stream().map(temp -> {
            ExternalInquiryListLogResponse responseLog = new ExternalInquiryListLogResponse();
            BeanUtils.copyProperties(temp, responseLog);
            responseLog.setStateName(InquiryExternalStatusEnum.getName(responseLog.getState()));
            return responseLog;
        }).collect(Collectors.toList());
        response.setExternalInquiryListLogResponses(externalInquiryListLogResponses);
    }


    /**
     * 询价单内部操作流程记录和状态数据配置
     */
    private void getInteriorLog(AppletInquiryDetailsResponse inquiryListDetailsResponse, Long id, UserLoginCacheDTO sysUser) {
        List<InquiryInteriorRecord> allByRequisitionFormIdEquals = inquiryInteriorRecordRepository.findAllByInquiryListIdEquals(id);
        //查询内部流转
        InternalProcessQueryVO taskParamQueryVO = new InternalProcessQueryVO();
        taskParamQueryVO.setMemberId(sysUser.getMemberId());
        taskParamQueryVO.setProcessKey(ProcessEnum.TRADE_INQUIRY_INNER.getProcessKey());
        Wrapper<SimpleProcessDefVO> listWrapper = processFeign.findSimpleInternalTaskDefinitions(taskParamQueryVO);
        List<LogStateResponse> interiorList = new ArrayList<>();
        if (ResponseCode.SUCCESS.getCode() != listWrapper.getCode()) {
            throw new RuntimeException(listWrapper.getMessage());
        }
        List<SimpleTaskVO> data = listWrapper.getData().getTasks();
        data.forEach(taskStepQueryVO -> {
            LogStateResponse quotationState = new LogStateResponse();
            quotationState.setOperationalProcess(taskStepQueryVO.getTaskName());
            quotationState.setRoleName(taskStepQueryVO.getRoleName());
            if (!CollectionUtils.isEmpty(allByRequisitionFormIdEquals)) {
                int state = allByRequisitionFormIdEquals.get(allByRequisitionFormIdEquals.size() - 1).getState() - 1;
                quotationState.setIsExecute(state >= taskStepQueryVO.getTaskStep() ? OrderConstant.State.START : OrderConstant.State.STOP);
            } else {
                quotationState.setIsExecute(OrderConstant.State.STOP);
            }
            quotationState.setState(taskStepQueryVO.getTaskStep());
            interiorList.add(quotationState);
        });
        if (!CollectionUtils.isEmpty(interiorList)) {
            interiorList.get(0).setIsExecute(OrderConstant.State.START);
        }
        inquiryListDetailsResponse.setInteriorRequisitionFormStateResponses(interiorList);
        if (CollectionUtils.isEmpty(allByRequisitionFormIdEquals)) {
            return;
        }
        List<InteriorInquiryListLogResponse> response = allByRequisitionFormIdEquals.stream().map(temp -> {
            InteriorInquiryListLogResponse interiorInquiryListLogResponse = new InteriorInquiryListLogResponse();
            BeanUtils.copyProperties(temp, interiorInquiryListLogResponse);
            interiorInquiryListLogResponse.setStateName(InquiryInteriorStatusEnum.getName(interiorInquiryListLogResponse.getState()));
            return interiorInquiryListLogResponse;
        }).collect(Collectors.toList());
        inquiryListDetailsResponse.setInteriorInquiryListLogResponses(response);
    }

}
